Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery delete trigger conditionally

I was wondering if Javascript or jQuery have a way to delete an event listener. Let's say I want to make a function that I want to trigger only once, for example let's say I want to have a button that shows some hidden elements on the document, I would make this function (assuming the hidden elements have a hidden class that hides them):

jQuery('#toggler').click(function() {
    console.log('Hidden elements are now shown');
    jQuery('.hidden').removeClass('hidden');
});

Simple enough, right ? Now, my actual problem comes in, I don't want jquery to run that function again and again each time the button is clicked, because the elements are already revealed, so is there a clean way to do it ? So, in this example after clicking the toggler multiple times I want to get only one console message.

I could do jQuery(this).unbind('click'), but this results into removing ALL triggers and I only want to remove the current trigger.

What I usually do when I face such scenarios is solve it like this (which is ugly and doesn't actually prevent code execution, but only handles the code's 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 don't want to use jQuery's one, because I will have the same problem when I'll need to delete the trigger conditionally, so if you can help please give me a dynamic answer.

Thanks in advance !

like image 922
George Dimitriadis Avatar asked Dec 08 '22 19:12

George Dimitriadis


2 Answers

You have to name your function like that:

var myFunction = function() {
    console.log('Hidden elements are now shown');
    jQuery('.hidden').removeClass('hidden');
};

And bind it this way

jQuery('#toggler').click(myFunction);

Then you can unbind it with :

jQuery('#toggler').off('click',myFunction);

Without unbinding the other listeners

like image 109
Alex C Avatar answered Dec 10 '22 07:12

Alex C


You can try this:

var myFunc = function() {
    console.log('Hidden elements are now shown');
    jQuery('.hidden').removeClass('hidden');
    jQuery(this).unbind('click', myFunc);
};
jQuery('#toggler').click(myFunc);

This way of calling unbind is such that only the listener for myFunc handler is removed and not all the events connected to the click on the toggler.

like image 34
pinturic Avatar answered Dec 10 '22 08:12

pinturic