Event.preventDefault () on first click, then delete

I have disabled the default anchor if it has a subnav class, as shown in this script .

I want this to be disabled for the first click, then I want to return the normal binding function. What is the best way to do this? I tried something using the code below, but that didn't work?

$(this).unbind(event.preventDefault()); 

maybe something like this psuedo code?

 if (click count === 0 ) { event.preventDefault(); } 

or is there a better way to approach this?

+6
source share
5 answers

You can pass false to one () :

 $(".subnav a").one("click", false); 

Passing false instead of a handler is equivalent to passing a handler that returns false , effectively stopping the propagation of the event and preventing its default behavior.

This is explained in the documentation for bind () :

In jQuery 1.4.3, you can pass false instead of an event handler. This will bind an event handler equivalent to: function() { return false; } function() { return false; } .

+5
source

Associate an event handler with one() document . It performs once and automatically unfastens itself subsequently.

 $(".subnav a").one("click", function(event) { event.preventDefault(); }); 

Alternatively, you can untie it directly directly in the function. It’s good to use a namespace for this

 $(".subnav a").bind("click.myclick", function(event) { event.preventDefault(); $(this).unbind(".myclick"); }); 
+8
source

It works well. The second click goes to the page ...

 $(".smallNavigation > ul > li > a").click(function (e) { $("ul.sub-menu").hide(); $("ul.sub-menu", $(this).parent("li")).show(); e.preventDefault(); $(this).unbind(e); } 
+5
source

it will work for you

 $("#elementid").bind("click", function( event ) { alert("This will be displayed only once."); event.preventDefault(); $(this).unbind( event ); }); 
0
source

You can use something as simple as self unbind in a click handler.

Sort of

 function stopEventOnce(event) { event.preventDefault(); $(this).unbind('click',stopEventOnce); return false; } $(".subnav a").bind('click', stopEventOnce); 

Modified violin

0
source

Source: https://habr.com/ru/post/921917/


All Articles