2

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

0

3 Answers 3

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;
  });
});
Sign up to request clarification or add additional context in comments.

3 Comments

never knew you could pass a function as the second parameter for jQuery, amazing
Only slight problem here is @thecodeparadox is that after the initial switch, it doesn't switch back again. So it goes from img1 to img2 and then doesn't go back to img again. Does that make any sense?
Sorry, my fault, must have been a typo. Works now. Many thanks.
1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.