admin管理员组

文章数量:1355748

I am trying to make a function that would allow me to toggle eventListener of an element.

In the example below, I have three buttons: main, on and off. When I click on the on button, the main button bees functional. After I click off button, the main button should not work anymore (but now it still does).

Now I can achieve a desired behavior by clicking on button for the second time, but I guess it's a bad coincidence and it's not supposed to work that way.

Maybe I should add that I would like to work this out without using jQuery or similar and it needs to be a function, because I am going to use it for a lot of buttons.

(I suspect something with scope causes the problem (clickHandler when calling the function to activate the button is not the same as the clickHandler when calling the function to disable the button), but I can't think of a way to test it.)

// buttons definitions, not important
var mainButton = document.querySelector("#mainButton");
var onButton = document.querySelector("#onButton");
var offButton = document.querySelector("#offButton");

// main function
var toggleButtons = function(toggleVal, button, element) {
    var activateButton, clickHandler, disableButton;

    // callback function for listener bellow
    clickHandler = function() {
        document.querySelector(element).classList.toggle("yellow");
    };

    activateButton = function() {
        button.addEventListener("click", clickHandler);
    };
    disableButton = function() {
        button.removeEventListener("click", clickHandler);
    };

    // when first argument is 1, make the button functional, otherwise disable its functionality
    if (toggleVal === 1) {
        activateButton();
    } else {
        disableButton();
    }
};

// when onButton is clicked, call main function with arguments
// this works
onButton.addEventListener("click", function() {
    toggleButtons(1, mainButton, "body");
});

// this fails to disable the button
offButton.addEventListener("click", function() {
    toggleButtons(0, mainButton);
});
.yellow {
  background-color: yellow;
}
<button type="button" id="mainButton">mainButton
</button>
<button type="button" id="onButton">onButton
</button>
<button type="button" id="offButton">offButton
</button>
<p>mainButton: toggles background color on click
</p>
<p>onButton: turns on mainButtons's functionality</p>
<p>offButton: supposed to turn off mainButton's functionality</p>

I am trying to make a function that would allow me to toggle eventListener of an element.

In the example below, I have three buttons: main, on and off. When I click on the on button, the main button bees functional. After I click off button, the main button should not work anymore (but now it still does).

Now I can achieve a desired behavior by clicking on button for the second time, but I guess it's a bad coincidence and it's not supposed to work that way.

Maybe I should add that I would like to work this out without using jQuery or similar and it needs to be a function, because I am going to use it for a lot of buttons.

(I suspect something with scope causes the problem (clickHandler when calling the function to activate the button is not the same as the clickHandler when calling the function to disable the button), but I can't think of a way to test it.)

// buttons definitions, not important
var mainButton = document.querySelector("#mainButton");
var onButton = document.querySelector("#onButton");
var offButton = document.querySelector("#offButton");

// main function
var toggleButtons = function(toggleVal, button, element) {
    var activateButton, clickHandler, disableButton;

    // callback function for listener bellow
    clickHandler = function() {
        document.querySelector(element).classList.toggle("yellow");
    };

    activateButton = function() {
        button.addEventListener("click", clickHandler);
    };
    disableButton = function() {
        button.removeEventListener("click", clickHandler);
    };

    // when first argument is 1, make the button functional, otherwise disable its functionality
    if (toggleVal === 1) {
        activateButton();
    } else {
        disableButton();
    }
};

// when onButton is clicked, call main function with arguments
// this works
onButton.addEventListener("click", function() {
    toggleButtons(1, mainButton, "body");
});

// this fails to disable the button
offButton.addEventListener("click", function() {
    toggleButtons(0, mainButton);
});
.yellow {
  background-color: yellow;
}
<button type="button" id="mainButton">mainButton
</button>
<button type="button" id="onButton">onButton
</button>
<button type="button" id="offButton">offButton
</button>
<p>mainButton: toggles background color on click
</p>
<p>onButton: turns on mainButtons's functionality</p>
<p>offButton: supposed to turn off mainButton's functionality</p>

Share Improve this question edited Sep 15, 2019 at 15:07 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jun 11, 2016 at 15:49 lukaslukas 5992 gold badges10 silver badges17 bronze badges 6
  • You have a typo offButon. – gcampbell Commented Jun 11, 2016 at 16:23
  • (P.S. you could just use true and false for toggleVal.) – gcampbell Commented Jun 11, 2016 at 16:24
  • Thank you, the typo is (unfortunately) not the reason the code is not working :( True/false is of course an option, it just made semantical sense to me that 1 = on, and 0 = off. – lukas Commented Jun 11, 2016 at 16:30
  • I would not do this by constantly switching event handlers on and off ... rather just set a flag (maybe on the element itself, as a custom data attribute) that tells the one initial handler, "should I react to this click event, or just let it pass by this time?" – C3roe Commented Jun 11, 2016 at 16:41
  • 1 @CBroe +1000000 to you! I spent days trying to figure this out only to find out that the solution is this simple <3 – lukas Commented Jun 11, 2016 at 17:43
 |  Show 1 more ment

2 Answers 2

Reset to default 2
var mainButton = document.querySelector("#mainButton");
var onButton = document.querySelector("#onButton");
var offButon = document.querySelector("#offButton");

var element; // declare the element here and change it from toggleButtons when needed.

function clickHandler() {
    document.querySelector(element).classList.toggle('yellow');
}
function activateButton(button) { // You missed this part
    button.addEventListener('click', clickHandler);
}
function disableButton(button) { // You missed this part
    button.removeEventListener('click', clickHandler);
}

function toggleButtons(value, button) {    
    if (value === 1) {
        activateButton(button);  // You missed this part
    } else {
        disableButton(button);  // You missed this part
    }
};

onButton.addEventListener('click', function() {
    element = 'body'; // you can change it to some other element 
    toggleButtons(1, mainButton);
});
offButton.addEventListener('click', function() {
    element = 'body'; // you can change it to some other element 
    toggleButtons(0, mainButton);
});

Below code helps to toggle between two functions from an eventListener:

   var playmusic=false;
    function playSound() {
      const audio = document.querySelector(`audio[data-key="${event.keyCode}"]`)
      audio.currentTime = 0
      audio.play()
      playmusic=true;
    }
    function stopSound() {
      const audio = document.querySelector(`audio[data-key="${event.keyCode}"]`)
      audio.pause()
      playmusic=false;
    }
    
    window.addEventListener('keydown',
    function(){playmusic?stopSound():playSound()} )

本文标签: javascriptToggle Event ListenersStack Overflow