Sayed Rafeeq Sayed Rafeeq - 4 months ago 94
jQuery Question

How to jQuery toggle multiple images on-click on image?

I'm trying to create a jQuery toggle with multiple images, I want to toggle on image(change image) onClick.

Note: My demo code working I'm looking for feature like...If I clicked on the first image it will change when I click on second image the first will change to normal stage it will repeat with third image also.

Demo code:



$("#infoToggler").click(function() {
$(this).find('img').toggle();
});
$("#infoToggler2").click(function() {
$(this).find('img').toggle();
});
$("#infoToggler3").click(function() {
$(this).find('img').toggle();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="infoToggler"><img src="http://tympanus.net/PausePlay/images/play.png" width="60px" height="60px"/>
<img src="http://tympanus.net/PausePlay/images/pause.png" width="60px" height="60px" style="display:none"/>
</div>

<div id="infoToggler2"><img src="http://tympanus.net/PausePlay/images/play.png" width="60px" height="60px"/>
<img src="http://tympanus.net/PausePlay/images/pause.png" width="60px" height="60px" style="display:none"/>
</div>

<div id="infoToggler3"><img src="http://tympanus.net/PausePlay/images/play.png" width="60px" height="60px"/>
<img src="http://tympanus.net/PausePlay/images/pause.png" width="60px" height="60px" style="display:none"/>
</div>





I found these links on Stack Overflow but they're not what I'm looking for.

jQuery Toggle on click of image

How to jQuery toggle multiple images on different button click?

Answer

First, work with classes rather than IDs, then you only need one handler, not multiple. So, give the divs a class.

Next, give the 'reset' image one class and the other a different one. This allows you to reset the others.

Html:

<div class='toggler'>
    <img class='orig' src="http://tympanus.net/PausePlay/images/play.png" width="60px" height="60px"/>
    <img class='alt'  src="http://tympanus.net/PausePlay/images/pause.png" width="60px" height="60px" style="display:none"/>
</div>

<div class='toggler'>
    <img class='orig' src="http://tympanus.net/PausePlay/images/play.png" width="60px" height="60px"/>
    <img class='alt'  src="http://tympanus.net/PausePlay/images/pause.png" width="60px" height="60px" style="display:none"/>
</div>

<div class='toggler'>
    <img class='orig' src="http://tympanus.net/PausePlay/images/play.png" width="60px" height="60px"/>
    <img class='alt'  src="http://tympanus.net/PausePlay/images/pause.png" width="60px" height="60px" style="display:none"/>
</div>

You can then add a handler to the div to toggle images in that div and reset all others:

$(".toggler").click(function() {

    // Reset all images
    $(".toggler img.alt").hide();
    $(".toggler img.orig").show();

    // Now toggle the ones in this .toggler
    $("img", this).toggle();
});