0

Is there a way to toggle the src attribute of an image between two values when an anchor is clicked?

Like this:

$('a#some-anchor').click(function() {
// code here that toggles between two image src's e.g. "images/some-image1.jpg" and "images/some-image2.jpg"
});

5 Answers 5

8
$("img").bind("click", function() {
  var src = ($(this).attr("src") === "img1_on.jpg")
                ? "img2_on.jpg" 
                : "img1_on.jpg";
  $(this).attr("src", src);
});

Taken from here:

Changing the image source using jQuery

Sign up to request clarification or add additional context in comments.

Comments

2

Using internal data() function could work:

$('a#some-anchor').click(function() {
  var img = $(this);
  if ( img.data('active') ) {
    img.attr('src', 'images/some-image1.jpg');
    img.data('active', false);
  } else {
    img.attr('src', 'images/some-image2.jpg');
    img.data('active', true);
  }
});

Comments

2

Don't know where you image are but:

$('a#some-anchor').click(function() {
    var img = $('selector');

    if (img.attr('src').match(/image1/)) {
        img.attr('src', 'images/some-image2.jpg');
    } else {
        img.attr('src', 'images/some-image1.jpg');
    }
});

Comments

1
$('a#some-anchor').click(function() {
    var img = $('#yourIMG');

    var img1 = "images/some-image1.jpg";
    var img2 = "images/some-image2.jpg";

    img.attr('src', img.attr('src') == img1 ? img2 : img1);
});

Comments

0

Checkout this snippet:

var plus = 'https://d30y9cdsu7xlg0.cloudfront.net/png/5805-200.png';
var minus = 'https://d30y9cdsu7xlg0.cloudfront.net/png/5802-200.png';

$('#magic-toggle').click(function() {
  if ($('.fun-img').attr('src') === plus) {
    $('.fun-img').attr('src', minus);
  } else {
    $('.fun-img').attr('src', plus)
  }
})
.fun-img {
  width: 80px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://d30y9cdsu7xlg0.cloudfront.net/png/5805-200.png" class="fun-img" id="magic-toggle">

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.