I am using this HTML on my site:
<a href="#1" id="slick-toggle"><img src="img1.jpg"/></a>
When I click this link, I would like to change the image src to img2.jpg
. And revert back to img1.jpg
when clicked again & so on. Can someone explain how I do this using jQuery?
Here is my existing jQuery if this helps:
$(document).ready(function() {
$('#slick-toggle').click(function() {
$('#slickbox').toggle(400);
return false;
});
});
Many thanks for any pointers with this :-)
I am using this HTML on my site:
<a href="#1" id="slick-toggle"><img src="img1.jpg"/></a>
When I click this link, I would like to change the image src to img2.jpg
. And revert back to img1.jpg
when clicked again & so on. Can someone explain how I do this using jQuery?
Here is my existing jQuery if this helps:
$(document).ready(function() {
$('#slick-toggle').click(function() {
$('#slickbox').toggle(400);
return false;
});
});
Many thanks for any pointers with this :-)
Share Improve this question asked Dec 15, 2012 at 18:11 michaelmcgurkmichaelmcgurk 6,50925 gold badges100 silver badges197 bronze badges 03 Answers
Reset to default 8$(document).ready(function() {
$('#slick-toggle').click(function() {
$('img', this).attr('src', function(i, oldSrc) {
return oldSrc == 'img1.jpg' ? 'img2.jpg' : 'img1.jpg';
});
$('#slickbox').toggle(400);
return false;
});
});
You need to find the image inside since your click handler is on the that wraps it, like this:
$('a#slick-toggle').click(function() {
var img = $('#share')[0], isSwap = "True";
img.src = isSwap ? img.src.replace("_img1","_img2") : img.src.replace("_img2","_img1");
$('.img-swap').toggleClass("on");
$('#atBox').toggle(100);
return false;
});
Use this function for this:
$('#mylink').toggle(
function(){
$(this).attr('src','img2.jpg');
},
function(){
$(this).attr('src','img3.jpg');
}
// and so on..
);
you can add more function in it...