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"
});
timkl
  • 3,299
  • 12
  • 57
  • 71

5 Answers5

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

Community
  • 1
  • 1
benhowdle89
  • 36,900
  • 69
  • 202
  • 331
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);
  }
});
joksnet
  • 2,305
  • 15
  • 18
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');
    }
});
fredrik
  • 17,537
  • 9
  • 51
  • 71
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);
});
thirtydot
  • 224,678
  • 48
  • 389
  • 349
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">
BrokenBinary
  • 7,731
  • 3
  • 43
  • 54