Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you stop and then start / trigger an event with JQuery?

I'm trying to stop the default action when a link is clicked. Then I ask for confirmation and if confirmed I want to continue the event. How do I do this? I can stop the event but can't start it. Here's what I have so far:

$(document).ready(function(){
  $(".del").click(function(event) {
    event.preventDefault();
    if (confirm('Are you sure to delete this?')) {
      if (event.isDefaultPrevented()) {
        //let the event fire. how?
      }
    }
  });
});
like image 827
vagabond Avatar asked Jan 25 '10 08:01

vagabond


People also ask

What is trigger event in jQuery?

The trigger() method triggers the specified event and the default behavior of an event (like form submission) for the selected elements. This method is similar to the triggerHandler() method, except that triggerHandler() does not trigger the default behavior of the event.

Which method is used to stop default triggering action in jQuery?

The preventDefault() Method in jQuery is used to stop the default action of selected element to occur.


1 Answers

There's no need to prevent default to start. Just do this:

$(function() {
  $(".del").click(function(evt) {
    if (!confirm("Are you sure you want to delete this?")) {
      evt.preventDefault();
    }
  });
});

It's easier and more logical to prevent the event once you need to rather than preventing it and then un-preventing it (if that's even possible).

Remember that the code will stop running when the confirm box is presented to the user until the user selects OK or Cancel.

By the way, take a look at JavaScript: event.preventDefault() vs return false. Depending on if you want to stop the event propagation or not you may want to either call stopPropagation() or return false:

$(function() {
  $(".del").click(function(evt) {
    if (!confirm("Are you sure you want to delete this?")) {
      return false;
    }
  });
});
like image 184
cletus Avatar answered Oct 06 '22 00:10

cletus