[javascript] 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>
   </div>
</div>

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?

This question is related to javascript jquery image

The answer is


Short but exact

$("#d1 img").click(e=> e.target.src= pic[e.target.src.match(pic[0]) ? 1:0] );

_x000D_
_x000D_
let pic=[
  "https://picsum.photos/id/237/40/40", // arbitrary - eg: "img1_on.gif",
  "https://picsum.photos/id/238/40/40", // arbitrary - eg: "img2_on.gif"
];

$("#d1 img").click(e=> e.target.src= pic[e.target.src.match(pic[0]) ? 1:0] );
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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


I made a codepen with exactly this functionality here. I will give you a breakdown of the code here as well.

Codepen

_x000D_
_x000D_
$(function() {

  //Listen for a click on the girl button
  $('#girl-btn').click(function() {

    // When the girl button has been clicked, change the source of the #square image to be the girl PNG
    $('#square').prop("src", "https://homepages.cae.wisc.edu/~ece533/images/girl.png");
  });

  //Listen for a click on the plane button
  $('#plane-btn').click(function() {

    // When the plane button has been clicked, change the source of the #square image to be the plane PNG
    $('#square').prop("src", "https://homepages.cae.wisc.edu/~ece533/images/airplane.png");
  });

  //Listen for a click on the fruit button
  $('#fruits-btn').click(function() {

    // When the fruits button has been clicked, change the source of the #square image to be the fruits PNG
    $('#square').prop("src", "https://homepages.cae.wisc.edu/~ece533/images/fruits.png");
  });
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<img src="https://homepages.cae.wisc.edu/~ece533/images/girl.png" id="square" />
<div>
  <button id="girl-btn">Girl</button>
  <button id="plane-btn">Plane</button>
  <button id="fruits-btn">Fruits</button>

  <a href="https://homepages.cae.wisc.edu/~ece533/images/">Source of Images</a>
</div>
_x000D_
_x000D_
_x000D_


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) { 

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

    });
});

The breakdown

  1. 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();  ;
    
  2. 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;
    
  3. 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") ); 
    
  4. 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") );
            event.preventDefault();
        });
    

    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


You can also do this with jQuery in this way:

$(".c1 img").click(function(){
     $(this).attr('src','/new/image/src.jpg');   
});

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


Hope this can work

<img id="dummyimage" src="http://dummyimage.com/450x255/" alt="" />
<button id="changeSize">Change Size</button>
$(document).ready(function() {
    var flag = 0;
    $("button#changeSize").click(function() {
        if (flag == 0) {
            $("#dummyimage").attr("src", "http://dummyimage.com/250x155/");
            flag = 1;
        } else if (flag == 1) {
            $("#dummyimage").attr("src", "http://dummyimage.com/450x255/");
            flag = 0;
        }
    });
});

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" 
    onclick="this.src=this.src.match(/_on/)?'img1_off.jpg':'img1_on.jpg';">
<img src="img2_on.jpg" 
    onclick="this.src=this.src.match(/_on/)?'img2_off.jpg':'img2_on.jpg';">

This can be written general and more elegant:

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

I had the same problem when trying to call re captcha button. After some searching, now the below function works fine in almost all the famous browsers(chrome,Firefox,IE,Edge,...):

function recaptcha(theUrl) {
  $.get(theUrl, function(data, status){});
  $("#captcha-img").attr('src', "");
  setTimeout(function(){
       $("#captcha-img").attr('src', "captcha?"+new Date().getTime());
  }, 0);
 }

'theUrl' is used to render new captcha image and can be ignored in your case. The most important point is generating new URL which forces FF and IE to rerender the image.


Just an addition, to make it even more tiny:

$('#imgId').click(function(){
    $(this).attr("src",$(this).attr('src') == 'img1_on.gif' ? 'img1_off.gif':'img1_on.gif');
});

This is a guaranteed way to get it done in Vanilla (or simply Pure) JavaScript:

var picurl = 'pictures/apple.png';
document.getElementById("image_id").src=picurl;

Change the image source using jQuery click()

element:

    <img class="letstalk btn"  src="images/chatbuble.png" />

code:

    $(".letstalk").click(function(){
        var newsrc;
        if($(this).attr("src")=="/images/chatbuble.png")
        {
            newsrc="/images/closechat.png";
            $(this).attr("src", newsrc);
        }
        else
        {
            newsrc="/images/chatbuble.png";
            $(this).attr("src", newsrc);
        }
    });

There is no way of changing the image source with CSS.

Only possible way is using Javascript or any Javascript library like jQuery.

Logic-

The images are inside a div and there are no class or id with that image.

So logic will be select the elements inside the div where the images are located.

Then select all the images elements with loop and change the image src with Javascript / jQuery.

Example Code with demo output-

_x000D_
_x000D_
$(document).ready(function()_x000D_
{_x000D_
    $("button").click(function()_x000D_
    {_x000D_
      $("#d1 .c1 a").each(function()_x000D_
      {_x000D_
          $(this).children('img').attr('src', 'https://www.gravatar.com/avatar/e56672acdbce5d9eda58a178ade59ffe');_x000D_
      });_x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>_x000D_
_x000D_
<div id="d1">_x000D_
   <div class="c1">_x000D_
            <a href="#"><img src="img1_on.gif"></a>_x000D_
            <a href="#"><img src="img2_on.gif"></a>_x000D_
   </div>_x000D_
</div>_x000D_
_x000D_
<button>Change The Images</button>
_x000D_
_x000D_
_x000D_


For more information. I try setting src attribute with attr method in jquery for ad image using the syntax for example: $("#myid").attr('src', '/images/sample.gif');

This solution is useful and it works but if changing the path change also the path for image and not working.

I've searching for resolve this issue but not found nothing.

The solution is putting the '\' at the beginning the path: $("#myid").attr('src', '\images/sample.gif');

This trick is very useful for me and I hope it is useful for other.


In case you update the image multiple times and it gets CACHED and does not update, add a random string at the end:

// update image in dom
$('#target').attr('src', 'https://example.com/img.jpg?rand=' + Math.random());

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="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') === 'img1_on.jpg')
            ? 'img2_on.jpg'
            : 'img1_on.jpg';
         $(this).attr('src', src);
    }
});

I have the same wonder today, I did on this way :

//<img src="actual.png" alt="myImage" class=myClass>
$('.myClass').attr('src','').promise().done(function() {
$(this).attr('src','img/new.png');  
});

You should add id attribute to your image tag, like this:

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

then you can use this code to change the source of images:

 $(document).ready(function () {
        $("#img1").attr({ "src": "logo-ex-7.png" });
        $("#img2").attr({ "src": "logo-ex-8.png" });
    });

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;   // Note: $(this).width() will not work for in memory images

});

Reason for editing: https://stackoverflow.com/a/670433/561545


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to image

Reading images in python Numpy Resize/Rescale Image Convert np.array of type float64 to type uint8 scaling values Extract a page from a pdf as a jpeg How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter? Angular 4 img src is not found How to make a movie out of images in python Load local images in React.js How to install "ifconfig" command in my ubuntu docker image? How do I display local image in markdown?