Changing the image source using jQuery

JavascriptJqueryImage

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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);
    }
});

Solution 2 - Javascript

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

Solution 3 - Javascript

> 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());

Solution 4 - Javascript

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.

Solution 5 - Javascript

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>

Solution 6 - Javascript

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

Solution 7 - Javascript

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;
		}
	});
});

Solution 8 - Javascript

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" });
    });

Solution 9 - Javascript

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.

Solution 10 - Javascript

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.

Solution 11 - Javascript

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);
        }
    });

Solution 12 - Javascript

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

Codepen

$(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");
  });
});

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

Solution 13 - Javascript

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');	
});

Solution 14 - Javascript

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;

Solution 15 - Javascript

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');
});

Solution 16 - Javascript

Short but exact

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

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] );

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

Solution 17 - Javascript

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-

$(document).ready(function()
{
    $("button").click(function()
    {
      $("#d1 .c1 a").each(function()
      {
          $(this).children('img').attr('src', 'https://www.gravatar.com/avatar/e56672acdbce5d9eda58a178ade59ffe');
      });
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/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>

<button>Change The Images</button>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser67033View Question on Stackoverflow
Solution 1 - JavascriptjonstjohnView Answer on Stackoverflow
Solution 2 - JavascriptMohsenView Answer on Stackoverflow
Solution 3 - JavascriptkintsukuroiView Answer on Stackoverflow
Solution 4 - JavascriptwphonestudioView Answer on Stackoverflow
Solution 5 - JavascriptincoView Answer on Stackoverflow
Solution 6 - JavascriptPeter AjtaiView Answer on Stackoverflow
Solution 7 - JavascriptZeeshanView Answer on Stackoverflow
Solution 8 - JavascriptMr BitmapView Answer on Stackoverflow
Solution 9 - JavascriptFernandoEscherView Answer on Stackoverflow
Solution 10 - JavascriptKayvan TehraniView Answer on Stackoverflow
Solution 11 - JavascriptAbhijit PoojariView Answer on Stackoverflow
Solution 12 - JavascriptNeil MeyerView Answer on Stackoverflow
Solution 13 - JavascriptAnyone_phView Answer on Stackoverflow
Solution 14 - JavascriptRaymond WachagaView Answer on Stackoverflow
Solution 15 - JavascriptSzél LajosView Answer on Stackoverflow
Solution 16 - JavascriptKamil KiełczewskiView Answer on Stackoverflow
Solution 17 - JavascriptAbrar JahinView Answer on Stackoverflow