shingou
shingou

Reputation: 49

jQuery changing the source folder of multiple images

I'm trying to have my images source attributes to change when a certain button is clicked. I got this code as of the moment.

$('.palettemain #brown').click(function () {
    var imageName = $('.panestop span > img').attr('alt');
    var imageFolder = 'images/sitebuilder/logo/brown/';
    $('.panestop span > img').each(function () {
        $(this).attr('src', imageFolder + imageName);
    });
});

As you can see I have declared variable names for the image name and the image folder. when I click .palettemain #brown (the button) it loads the image, also fetching the correct folder name and image file name. The thing here is, only the first instance image file name is fetched. Below is the HTML code before the click happens.

   <span>
       <input type="radio" name="logo" checked="checked" />
       <img src="images/sitebuilder/logo/default/logo01.png" alt="logo01.png" />
   </span>
   <span>
       <input type="radio" name="logo" checked="checked" />
       <img src="images/sitebuilder/logo/default/logo02.png" alt="logo02.png" />
   </span>
   <span>
       <input type="radio" name="logo" checked="checked" />
       <img src="images/sitebuilder/logo/default/logo03.png" alt="logo03.png" />
   </span>

Below is the output when clicked:

   <span>
       <input type="radio" checked="checked" name="logo">
       <img alt="logo01.png" src="images/sitebuilder/logo/brown/logo01.png">
   </span>
   <span>
       <input type="radio" checked="checked" name="logo">
       <img alt="logo02.png" src="images/sitebuilder/logo/brown/logo01.png">
   </span>
   <span>
       <input type="radio" checked="checked" name="logo">
       <img alt="logo03.png" src="images/sitebuilder/logo/brown/logo01.png">
   </span>

The output, as you can see, is duplicating the first image alt attribute. How do I fetch the alt attribute for each instance of the image?

Upvotes: 1

Views: 2331

Answers (1)

Fender
Fender

Reputation: 3055

You only read the image name once from the alt attribute. Try:

$('.palettemain #brown').click(function () {
    var imageFolder = 'images/sitebuilder/logo/brown/';
    $('.panestop span > img').each(function () {
        imageName = $(this).attr('alt');
        $(this).attr('src', imageFolder + imageName);
    });
});

Upvotes: 1

Related Questions