Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

on/off click events in Jquery

I am trying to toggle a click event on and off to prevent multiple function calls. Below is my code. The click is turning off but I can't seem to turn it on again. Thoughts?

$("#element").click(function(){
     doit();
     $(this).off('click');
 })

function doit(){

    do stuff...

    //turn click back on
    $("#element").on('click');

}
like image 423
barrylachapelle Avatar asked Feb 15 '23 02:02

barrylachapelle


1 Answers

You need to pass the handler back to the on method, also use .one() as you want to fire it only once

function clickHandler() {
    doit();
}
$("#element").one('click', function () {})

function doit() {
    //do stuff...

    //turn click back on
    $("#element").one('click', clickHandler);
}
like image 183
Arun P Johny Avatar answered Feb 17 '23 01:02

Arun P Johny