简体   繁体   中英

Toggle images on click using jQuery

I have two images which I need to toggle on clicking on the image.

    <img id='arrowRotate' src='images/prof_arrow1.png' data-swap='images/prof_arrow.png' 
data-src='images/prof_arrow1.png' />

When the user click the image the src should get the value of data-swap and when you click again the src should change to data-src . This should keep happening just like a toggle. Any help appreciated.

$("#arrowRotate").click(function() {
    var swapImage = $("#arrowGrey").attr("data-swap");
    $("#arrowGrey").attr({
        'src': swapImage,
        id: 'arrowOrange'
    });
});  

This is where I have got so far.

Based on my understanding from your question, Hope this is the one you expect,

$("#arrowRotate").click(function() { 
      var _this = $(this);
      var current = _this.attr("src");
      var swap = _this.attr("data-swap");     
     _this.attr('src', swap).attr("data-swap",current);   
});  

DEMO Fiddle

Try This:

 $("#arrowRotate").click(function(){ if($(this).attr('src')==$(this).attr('data-src')) { var a = $(this).attr('data-swap'); $(this).attr('src',a); } else { var b = $(this).attr('data-src'); $(this).attr('src',b); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <img id='arrowRotate' src='http://www.gettyimages.in/CMS/StaticContent/1391099215267_hero2.jpg' data-swap='http://www.hdwallpapersimages.com/wp-content/uploads/2014/01/Winter-Tiger-Wild-Cat-Images.jpg' data-src='http://www.gettyimages.in/CMS/StaticContent/1391099215267_hero2.jpg'> 

This might help. I think this is the simplest way of swapping between images:

<img id="arrowRotate" src="images/img1.png" data-swap="images/img2.png" data-src="images/img1.png" onclick="swapImage()" />

function swapImage(){
    var swapImage = $('#arrowRotate').attr('data-swap'),
        currentImage = $('#arrowRotate').attr('src');

    $('#arrowRotate').attr({
        'src': swapImage,
        'data-swap': currentImage
    });
};

If I understand you right you can do it like this:

HTML

<img id='arrowRotate' src='images/prof_arrow1.png' data-swap='images/prof_arrow.png' data-src='images/prof_arrow1.png' data-swapped="false"/>

Javascript

$("#arrowRotate").click(function() {

    var swapped = $(this).attr("data-swapped");
    var init = 'false';

    if(swapped === 'false'){
        var swapImage = $(this).attr("data-swap");
        init = true;
    }else{
        var swapImage = $(this).attr("data-src");
    }

    $(this).attr({
        'src': swapImage,
        'id': 'arrowOrange',
        'data-swapped': init
    });

});  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM