I was wondering if Javascript or jQuery has a way to remove the event listener. Suppose I want to create a function that I want to run only once, for example, suppose I have a button that shows some hidden elements in a document, I would make this function (assuming that the hidden elements have a hiddenclass that their hides):
jQuery('#toggler').click(function() {
console.log('Hidden elements are now shown');
jQuery('.hidden').removeClass('hidden');
});
Simple enough, right? Now my actual problem comes up , I don’t want jquery to run this function again and again every time the button is clicked, because the elements are already detected, so there is a clean way to do it? So, in this example, after pressing the toggler button several times, I want to receive only one console message.
I could do it jQuery(this).unbind('click'), but this removes ALL triggers, and I only want to delete the current trigger.
What I usually do when I come across such scenarios resolves it this way (it is ugly and does not actually prevent code execution , but only processes code results):
var toggler_clicked = false;
jQuery('#toggler').click(function() {
if(toggler_clicked) return;
toggler_clicked = true;
console.log('Hidden elements are now shown');
jQuery('.hidden').removeClass('hidden');
});
Also I do not want to use jQuery onebecause I will have the same problem when I need to remove the trigger conditionally, so if you can help, please give me a dynamic answer.
Thanks in advance!
source
share