Sayed Rafeeq Sayed Rafeeq - 7 days ago 7
CSS Question

How to Play & Pause icons toggle on click?

I'm trying to create a jQuery toggle Play & Pause icons , I want to toggle icons onClick.

Note: My demo is code working but I'm looking for feature like...If I clicked on the first play icon and it will change.
When I click on second icon play it will change with pause icon then the first pause icon will change with play icon and it will repeat with third icon 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://c28.imgup.net/play-icon223d.png" width="60px" height="60px"/>
<img src="http://e52.imgup.net/stop-icon731e.png" width="60px" height="60px" style="display:none"/>
</div>

<div id="infoToggler2"><img src="http://c28.imgup.net/play-icon223d.png
" width="60px" height="60px"/>
<img src="http://e52.imgup.net/stop-icon731e.png" width="60px" height="60px" style="display:none"/>
</div>

<div id="infoToggler3"><img src="http://c28.imgup.net/play-icon223d.png" width="60px" height="60px"/>
<img src="http://e52.imgup.net/stop-icon731e.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://c28.imgup.net/play-icon223d.png" width="60px" height="60px"/>
    <img class='alt'  src="http://e52.imgup.net/stop-icon731e.png" width="60px" height="60px" style="display:none"/>
</div>

<div class='toggler'>
    <img class='orig' src="http://c28.imgup.net/play-icon223d.png" width="60px" height="60px"/>
    <img class='alt'  src="http://e52.imgup.net/stop-icon731e.png" width="60px" height="60px" style="display:none"/>
</div>

<div class='toggler'>
    <img class='orig' src="http://c28.imgup.net/play-icon223d.png" width="60px" height="60px"/>
    <img class='alt'  src="http://e52.imgup.net/stop-icon731e.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();
});
Comments