Changing the image source using jQuery
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); }});
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
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());