JavaScript help

Good Morning:

I’m trying to create a event that I saw on another website for a website that I am currently developing . The link is below:

As you can see, when you click a colored swatch below, the image above changes to match the color. How is this done? What “event” is this in JavaScript? Is there an easier way to do this in J-Query? Any information you have or a solution, would be greatly appreciated.


Hi Robby,

Welcome to Sitepoint.
You want to listen to a click event on the colors and change some state on the image to make it change, the src of the image or a class if you are using background images in css.

Here’s a pretty crude example using jQuery.

<img id="shirt" src="white.jpg">
<ul id="colors">

var shirts = {
  red: 'red.jpg',
  green: 'green.jpg',
  blue: 'blue.jpg'
var shirt = $('#shirt')[0];
$('#colors li').click(function() {
  var color = $(this).html();
  shirt.src = shirts[color];

The image should change right within the page…correct? On the click function?

Thanks a million, I’m going to try this solution out.

Yes, you want to update something on the image when you click a color.

Have a go, if you get stuck post a link to your page and we’ll take a look.