My DOM looks like this:

<div id="d1">
   <div class="c1">
            <a href="#"><img src="img1_on.gif"></a>
            <a href="#"><img src="img2_on.gif"></a>
   </div>
</div>

When someone clicks on an image, I want the image src to change to <img src="https://stackoverflow.com/questions/554273/imgx_off.gif"> where x represents the image number 1 or 2.

Is this possible or do I have to use CSS to change the images?

17 s
17

You can use jQuery’s attr() function. For example, if your img tag has an id attribute of ‘my_image’, you would do this:

<img id="my_image" src="https://stackoverflow.com/questions/554273/first.jpg"/>

Then you can change the src of your image with jQuery like this:

$("#my_image").attr("src","second.jpg");

To attach this to a click event, you could write:

$('#my_image').on({
    'click': function(){
        $('#my_image').attr('src','second.jpg');
    }
});

To rotate the image, you could do this:

$('img').on({
    'click': function() {
         var src = ($(this).attr('src') === "https://stackoverflow.com/questions/554273/img1_on.jpg")
            ? 'img2_on.jpg'
            : "https://stackoverflow.com/questions/554273/img1_on.jpg";
         $(this).attr('src', src);
    }
});

Leave a Reply

Your email address will not be published. Required fields are marked *