Sunday, June 10, 2012

Changing the image source using jQuery

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>

When someone clicks on an image, I want the image src to change to <img src="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?

Source: Tips4all


  1. You can use jQuery's attr() function. For example, if you img tag has an id attribute of 'my_image':

    <img id="my_image" src="first.jpg"/>

    Then you can change the src in jQuery by:


    To attach this to an onclick event, you could write:

    'click': function(){

    To rotate the image, you could do this:

    'click': function() {
    var src = ($(this).attr('src') === 'img1_on.jpg')
    ? 'img2_on.jpg'
    : 'img1_on.jpg';
    $(this).attr('src', src);

  2. I'll show you how to change the image src, so that when you click an image it rotates through all the images that are in your HTML (in your d1 id and c1 class specifically)... whether you have 2 or more images in your HTML.

    I'll also show you how to clean up the page after the document is ready, so that only one image is displayed initially.

    The full code

    $(function() {

    var $images = $("#d1 > .c1 > a").clone();

    var $length = $images.length;
    var $imgShow = 0;

    $("#d1 > .c1").html( $("#d1 > .c1 > a:first") );

    $("#d1 > .c1 > a").click(function(event) {

    $("img", $images).eq(++$imgShow % $length).attr("src") );


    The breakdown

    Create a copy of the links containing the images (note: you could also make use of the href attribute of the links for added functionality... for example display the working link below each image):

    var $images = $("#d1 > .c1 > a").clone(); ;

    Check how many images were in the HTML and create a variable to track which image is being shown:

    var $length = $images.length;
    var $imgShow = 0;

    Modify the document's HTML so that only the first image is being shown. Delete all the other images.

    $("#d1 > .c1").html( $("#d1 > .c1 > a:first") );

    Bind a function to handle when the image link is clicked.

    $("#d1 > .c1 > a").click(function(event) {
    $(this).children().attr("src", $("img", $images).eq(++$imgShow % $length).attr("src") );

    The heart of the above code is using ++$imgShow % $length to cycle through the jQuery object containing the images. ++$imgShow % $length first increases our counter by one, then it mods that number with how many images there are. This will keep the resultant index cycling from 0 to length-1, which are the indices of the $images object. This means this code will work with 2, 3, 5, 10, or 100 images... cycling through each image in order and restarting at the first image when the last image is reached.

    Additionally, .attr() is used to get and set the "src" attribute of the images. To pick elements from among the $images object, I set $images as the jQuery context using the form $(selector, context). Then I use .eq() to pick just the element with the specific index I'm interested in.

    jsFiddle example with 3 images

    You can also store the srcs in an array.
    jsFiddle example with 3 images

    And here's how to incorporate the hrefs from the anchor tags around the images:
    jsFiddle example

  3. If you want something using jQuery you might want to look into the jQuery Cycle Plugin, demo scrollRight (bottom-right example)

  4. You can also do this with jQuery in this way:

    $(".c1 img").click(function(){

    You can have a condition if there are multiple states for the image source.

  5. IF there is not only jQuery or other resource killing frameworks - many kb to download each time by each user just for a simple trick - but also native JavaScript(!):

    <img src="img1_on.jpg"
    <img src="img2_on.jpg"

    This can be written general and more elegant:

    function switchImg(img){
    img.src = img.src.match(/_on/) ?
    img.src.replace(/_on/, "_off") :
    img.src.replace(/_off/, "_on");
    <img src="img1_on.jpg" onclick="switchImg(this)">
    <img src="img2_on.jpg" onclick="switchImg(this)">

  6. One of the common mistakes people do when change the image source is not waiting for image load to do afterward actions like maturing image size etc.
    You will need to use jQuery .load() method to do stuff after image load.

    $('yourimageselector').attr('src', 'newsrc').load(function(){
    $(this).width(); // this is how you get new width of image