How to Change the image source using jQuery

by THavamani 2013-08-27 15:44:46

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:

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


To attach this to an onclick 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);
}
});
568
like
0
dislike
0
mail
flag

You must LOGIN to add comments