Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

event.preventDefault() on first click then remove

Tags:

jquery

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

I only want this disabled for the first click then I want the normal anchor functionality to be brought back. What is the best way to do this? I tried something involving the below code but this didn't seem to 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?

like image 813
ak85 Avatar asked Aug 02 '12 07:08

ak85


People also ask

What does event preventDefault () do?

Event.preventDefault() The preventDefault() method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.

How is preventDefault () Used with drag and drop?

In a web page, you should call the preventDefault() method of the event if you have accepted the drop, so that the browser's default handling is not triggered by the dropped data as well. For example, when a link is dragged to a web page, Firefox will open the link.

How do you stop a click event?

To stop an event from further propagation in the capturing and bubbling phases, you call the Event. stopPropation() method in the event handler. Note that the event. stopPropagation() method doesn't stop any default behaviors of the element e.g., link click, checkbox checked.

How do you reverse e preventDefault?

There is no opposite method of event. preventDefault() to understand why you first have to look into what event. preventDefault() does when you call it. Underneath the hood, the functionality for preventDefault is essentially calling a return false which halts any further execution.


2 Answers

Bind the event handler with one()docu. It executes once and automatically unbinds itself afterwards.

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

Alternatively you can unbind it yourself directly in the function. It's good to use a namespace for that

$(".subnav a").bind("click.myclick", function(event) {
  event.preventDefault();
  $(this).unbind(".myclick");
});
like image 82
Christoph Avatar answered Sep 21 '22 21:09

Christoph


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

}
like image 32
The Hawk Avatar answered Sep 20 '22 21:09

The Hawk