user2890068
user2890068

Reputation: 35

jQuery change image onClick from a link

I'm trying to use jQuery to rotate through images when a link is clicked, then go back to the original image again.

jQuery:

$(document).ready(function() {     
  $('#toggle').click(function() {
  $('img', this).attr('src', function(i, oldSrc) {
      return oldSrc == 'images/1.jpg' ? 'images/2.jpg' : 'images/1.jpg';
  });
  $('#link').toggle(400);
  return false;
  });
});

HTML

<a href="#" id="toggle">button</a>
<img src="images/1.jpg" height="68" width="216" alt="" id="#link" />

Not quite sure what wrong here, thanks for the help.

Upvotes: 0

Views: 781

Answers (3)

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try this,

HTML

<a href="#" id="toggle">button</a>
<img src="images/1.jpg" height="68" width="216" alt="" id="link" />

SCRIPT

$(document).ready(function () {
    $('#toggle').click(function () {
        $('#link').attr('src', function (i, oldSrc) {
            return oldSrc == 'images/1.jpg' ? 'images/2.jpg' : 'images/1.jpg';
        });
       $('#link').toggle(400);
        return false;
    });
});

Demo

Upvotes: 0

Richard Dalton
Richard Dalton

Reputation: 35793

There are a few things wrong:

$('img', this) will select image tags inside the link that was clicked. So, in this case it won't select anything.

$('#link').toggle(400); will show and hide the img on alternate clicks.

and finally as previously mentioned, the ID of the image should be link rather than #link.

To make your code work I would change it to this:

$('#toggle').click(function(e) {
  e.preventDefault();
  $('#link').attr('src', function(i, oldSrc) {
      return oldSrc == 'images/1.jpg' ? 'images/2.jpg' : 'images/1.jpg';
  });
});

And the image tag to this:

<img src="images/1.jpg" height="68" width="216" alt="" id="link" />

Upvotes: 0

Anthony Grist
Anthony Grist

Reputation: 38345

This bit of code:

$('img', this).attr('src', function(i, oldSrc) {
    return oldSrc == 'images/1.jpg' ? 'images/2.jpg' : 'images/1.jpg';
});

is looking for an image that's a descendent of the <a> element, which isn't the case with your given HTML (it's a sibling). It should instead be:

$(this).next('img').attr('src', function(i, oldSrc) {
    return oldSrc == 'images/1.jpg' ? 'images/2.jpg' : 'images/1.jpg';
});

And, as Anton has already said, the ID attribute for your image needs to be changed.

Upvotes: 1

Related Questions