خرید بک لینک

Vote count: 0

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 becomes 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.

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

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

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

    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);
});

// this fails to disable the button
offButton.addEventListener("click", function() {
    toggleButtons(0, mainButton);
});
.red {
  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: tus on mainButtons's functionality</p>
<p>offButton: supposed to tu off mainButton's functionality</p>
asked 1 min ago

برچسب: نویسنده: استخدام کار تاريخ: شنبه 22 خرداد 1395 ساعت: 23:05

صفحه بندی