Search code examples
javascriptjqueryfunctionsetinterval

on click Disable and Enable setInterval


Hi I am trying to disable the setInterval which I have done how ever I cannot enable it again and the class of my "mute" button doesn't change can someone point me in the right direction please here is my code

HTML:

<a href="#" class="MuteOff">button</a> 

Button:

$('.MuteOn').on('click tap touch', function() {
$('.MuteOn').removeClass("MuteOn").addClass("MuteOff"); //the class changes
clearInterval(MyTimer);
 });

$('.MuteOff').on('click tap touch', function() {
$('.MuteOff').removeClass("MuteOff").addClass("MuteOn"); //the class doesn't change back to MuteOn
MyTimer = setInterval(Checker, 100); //doesn't work
 });

Function:

var MyTimer = setInterval(Checker, 100);
 function Checker(){

if ($("body").hasClass("fp-viewing-1")) {
            audio1.play();
            }
           else {
   audio1.pause();
   audio1.currentTime = 0;
            }

if ($("body").hasClass("fp-viewing-2")) {
            audio2.play();
            }
           else {
   audio2.pause();
   audio2.currentTime = 0;
            }

if ($("body").hasClass("fp-viewing-3")) {
            audio3.play();
            }
           else {
   audio3.pause();
   audio3.currentTime = 0;
            }
}

Thank you for any help


Solution

  • I would add a common class for the mute button and when clicked, check for MuteOn/MuteOff class(or use a boolean) and do what you need to do.

    Your MuteOff click doesn't work because the MuteOff element doesn't exist on load.

    Set MuteOn/Off in the markup

    HTML

    <a href="#" class="mute-button MuteOff">button</a>
    

    JS

    $('.mute-button').on('click tap touch', function() {
        var $this = $(this);
    
        if( $this.hasClass("MuteOn") ) {
             // do mute off stuff
             $this.removeClass("MuteOn").addClass("MuteOff");
             clearInterval(MyTimer);
        } else {
             // do mute on stuff
             $this.removeClass("MuteOff").addClass("MuteOn");
             MyTimer = setInterval(Checker, 100);
        }
    });
    

    You can also use the event delegation way as @Santi mentioned, but the above might be easier to understand for now.

    Direct vs. Delegated - jQuery .on()