246

Once I've fired an evt.preventDefault(), how can I resume default actions again?

Black
  • 18,150
  • 39
  • 158
  • 271
Bryan
  • 2,461
  • 2
  • 15
  • 3
  • 3
    I think typically your function would run and then the default behavior would run, so you would never call evt.preventDefault() in the first place – Prescott Apr 13 '11 at 15:44
  • Can you give us an example of what you are trying to do? – Peter Olson Apr 13 '11 at 15:45
  • 1
    Possible duplicate? : http://stackoverflow.com/questions/1551389/how-to-enable-default-after-event-preventdefault – Nobita Apr 13 '11 at 15:47
  • 2
    @Nobita - I'm not so sure... that one is specific to jQuery. – gilly3 Apr 13 '11 at 15:54
  • 1
    Wow, thanx for the quick responses! My problem is though, that I'm not the one firing the evt.preventDefault();. I'm running a 3rd party flash application in a lightbox. When I close the lightbox, somehow my mousewheel for page scrolling stops. In doing some research, I found that this flash app disables page scrolling because of a zoom feature. So now I am trying to resume page scrolling once the app is closed. Maybe there is some method I can call to resume mouse wheel event? – Bryan Apr 13 '11 at 15:56
  • 2
    possible duplicate of [How to reenable event.preventDefault?](http://stackoverflow.com/questions/1164132/how-to-reenable-event-preventdefault) – Richard Ev Apr 13 '11 at 16:19
  • So looking at that link, how would a resume scrolling? `$(document).unbind('sroll').scroll()`? Not too sure on that one. – Bryan Apr 13 '11 at 16:32
  • 1
    possible duplicate of [how to re-enable default after doing event.preventDefault()](http://stackoverflow.com/questions/2608714/how-to-re-enable-default-after-doing-event-preventdefault), and [How to reenable event.preventDefault?](http://stackoverflow.com/questions/1164132/how-to-reenable-event-preventdefault) – Paŭlo Ebermann Nov 19 '11 at 18:57
  • Have you looked at this question & answer? http://stackoverflow.com/questions/1164132/how-to-reenable-event-preventdefault/1164177#1164177 – SavoryBytes Apr 13 '11 at 15:52
  • This is a valid concern - how would you re-enable the default given that this may have bubbled up the dom from other code? – James Westgate Jan 11 '14 at 22:05
  • Try the solution mentioned here. [enter link description here](https://stackoverflow.com/a/36319301/6098052) – Soumya Sengupta Nov 07 '19 at 09:03

20 Answers20

105

As per commented by @Prescott, the opposite of:

evt.preventDefault();

Could be:

Essentially equating to 'do default', since we're no longer preventing it.

Otherwise I'm inclined to point you to the answers provided by another comments and answers:

How to unbind a listener that is calling event.preventDefault() (using jQuery)?

How to reenable event.preventDefault?

Note that the second one has been accepted with an example solution, given by redsquare (posted here for a direct solution in case this isn't closed as duplicate):

$('form').submit( function(ev) {
     ev.preventDefault();
     //later you decide you want to submit
     $(this).unbind('submit').submit()
});
Community
  • 1
  • 1
Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
  • Thank you! Was scratching my head for awhile on this (I needed to stop and check a few things before a form submit, not submitting in certain circumstances, submitting in others). – Katharine Osborne Feb 19 '18 at 19:00
  • 1
    It does work but I don't understand why next form submit call the function again, I thought it'd unbind it definitely, but it looks like it unbind only for the current call... I can't explain it, it does exactly what I want but it's not what I'd have expected. – Vadorequest Oct 13 '18 at 21:41
  • `$(this).unbind('submit').submit()` is good but what if the event was `contextmenu`? You can't re-initiate that. – Jerry Green Dec 21 '22 at 11:05
52
function(evt) {evt.preventDefault();}

and its opposite

function(evt) {return true;}

cheers!

Andy Li
  • 5,894
  • 6
  • 37
  • 47
foxybagga
  • 4,184
  • 2
  • 34
  • 31
30

To process a command before continue a link from a click event in jQuery:

Eg: <a href="http://google.com/" class="myevent">Click me</a>

Prevent and follow through with jQuery:

$('a.myevent').click(function(event) {
    event.preventDefault();

    // Do my commands
    if( myEventThingFirst() )
    {
      // then redirect to original location
      window.location = this.href;
    }
    else
    {
      alert("Couldn't do my thing first");
    }
});

Or simply run window.location = this.href; after the preventDefault();

Bradley Flood
  • 10,233
  • 3
  • 46
  • 43
17

OK ! it works for the click event :

$("#submit").click(function(event){ 
  
   event.preventDefault();

  // -> block the click of the sumbit ... do what you want

  // the html click submit work now !
  $("#submit").unbind('click').click(); 

});
SNS Web
  • 179
  • 1
  • 3
  • Thanks! Exactly what I was looking for. Have the click event clicked again after doing some validation in the meantime. – nrod Jun 10 '21 at 10:11
15
event.preventDefault(); //or event.returnValue = false;

and its opposite(standard) :

event.returnValue = true;

source: https://developer.mozilla.org/en-US/docs/Web/API/Event/returnValue

user10625817
  • 151
  • 1
  • 3
8

I had to delay a form submission in jQuery in order to execute an asynchronous call. Here's the simplified code...

$("$theform").submit(function(e) {
    e.preventDefault();
    var $this = $(this);
    $.ajax('/path/to/script.php',
        {
        type: "POST",
        data: { value: $("#input_control").val() }
    }).done(function(response) {
        $this.unbind('submit').submit();
    });
});
Bobby Pearson
  • 81
  • 1
  • 1
  • Another option in this scenario might be to use input type="button" and bind to the click event instead of using input type="submit" and binding to the submit event. – Strixy Jun 19 '13 at 18:54
6

I would suggest the following pattern:

document.getElementById("foo").onsubmit = function(e) {
    if (document.getElementById("test").value == "test") {
        return true;
    } else {
        e.preventDefault();
    }
}

<form id="foo">
    <input id="test"/>
    <input type="submit"/>
</form>

...unless I'm missing something.

http://jsfiddle.net/DdvcX/

karim79
  • 339,989
  • 67
  • 413
  • 406
4

This is what I used to set it:

$("body").on('touchmove', function(e){ 
    e.preventDefault(); 
});

And to undo it:

$("body").unbind("touchmove");
Joe McLean
  • 184
  • 2
  • 8
4

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. If you’re familiar with the old ways of Javascript, it was once in fashion to use return false for canceling events on things like form submits and buttons using return true (before jQuery was even around).

As you probably might have already worked out based on the simple explanation above: the opposite of event.preventDefault() is nothing. You just don’t prevent the event, by default the browser will allow the event if you are not preventing it.

See below for an explanation:

;(function($, window, document, undefined)) {

    $(function() {
        // By default deny the submit
        var allowSubmit = false;

        $("#someform").on("submit", function(event) {

            if (!allowSubmit) {
                event.preventDefault();

                // Your code logic in here (maybe form validation or something)
                // Then you set allowSubmit to true so this code is bypassed

                allowSubmit = true;
            }

        });
    });

})(jQuery, window, document);

In the code above you will notice we are checking if allowSubmit is false. This means we will prevent our form from submitting using event.preventDefault and then we will do some validation logic and if we are happy, set allowSubmit to true.

This is really the only effective method of doing the opposite of event.preventDefault() – you can also try removing events as well which essentially would achieve the same thing.

Partha
  • 402
  • 4
  • 15
4

Here's something useful...

First of all we'll click on the link , run some code, and than we'll perform default action. This will be possible using event.currentTarget Take a look. Here we'll gonna try to access Google on a new tab, but before we need to run some code.

<a href="https://www.google.com.br" target="_blank" id="link">Google</a>

<script type="text/javascript">
    $(document).ready(function() {
        $("#link").click(function(e) {

            // Prevent default action
            e.preventDefault();

            // Here you'll put your code, what you want to execute before default action
            alert(123); 

            // Prevent infinite loop
            $(this).unbind('click');

            // Execute default action
            e.currentTarget.click();
        });
    });
</script>
Rafael Xavier
  • 956
  • 13
  • 13
3

None of the solutions helped me here and I did this to solve my situation.

<a onclick="return clickEvent(event);" href="/contact-us">

And the function clickEvent(),

function clickEvent(event) {
    event.preventDefault();
    // do your thing here

    // remove the onclick event trigger and continue with the event
    event.target.parentElement.onclick = null;
    event.target.parentElement.click();
}
Raza
  • 3,147
  • 2
  • 31
  • 35
3

I supose the "opposite" would be to simulate an event. You could use .createEvent()

Following Mozilla's example:

function simulateClick() {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  var cb = document.getElementById("checkbox"); 
  var cancelled = !cb.dispatchEvent(evt);
  if(cancelled) {
    // A handler called preventDefault
    alert("cancelled");
  } else {
    // None of the handlers called preventDefault
    alert("not cancelled");
  }
}

Ref: document.createEvent


jQuery has .trigger() so you can trigger events on elements -- sometimes useful.

$('#foo').bind('click', function() {
      alert($(this).text());
});

$('#foo').trigger('click');
Nicholas Shanks
  • 10,623
  • 4
  • 56
  • 80
Gary Green
  • 22,045
  • 6
  • 49
  • 75
3

This is not a direct answer for the question but it may help someone. My point is you only call preventDefault() based on some conditions as there is no point of having an event if you call preventDefault() for all the cases. So having if conditions and calling preventDefault() only when the condition/s satisfied will work the function in usual way for the other cases.

$('.btnEdit').click(function(e) {

   var status = $(this).closest('tr').find('td').eq(3).html().trim();
   var tripId = $(this).attr('tripId');

  if (status == 'Completed') {

     e.preventDefault();
     alert("You can't edit completed reservations");

 } else if (tripId != '') {

    e.preventDefault();
    alert("You can't edit a reservation which is already attached to a trip");
 }
 //else it will continue as usual

});
Peck_conyon
  • 221
  • 2
  • 13
1

jquery on() could be another solution to this. escpacially when it comes to the use of namespaces.

jquery on() is just the current way of binding events ( instead of bind() ). off() is to unbind these. and when you use a namespace, you can add and remove multiple different events.

$( selector ).on("submit.my-namespace", function( event ) {
    //prevent the event
    event.preventDefault();

    //cache the selector
    var $this = $(this);

    if ( my_condition_is_true ) {
        //when 'my_condition_is_true' is met, the binding is removed and the event is triggered again.
        $this.off("submit.my-namespace").trigger("submit");
    }
});

now with the use of namespace, you could add multiple of these events and are able to remove those, depending on your needs.. while submit might not be the best example, this might come in handy on a click or keypress or whatever..

honk31
  • 3,895
  • 3
  • 31
  • 30
1

In a Synchronous flow, you call e.preventDefault() only when you need to:

a_link.addEventListener('click', (e) => {
   if( conditionFailed ) {
      e.preventDefault();
      // return;
   }

   // continue with default behaviour i.e redirect to href
});

In an Asynchronous flow, you have many ways but one that is quite common is using window.location:

a_link.addEventListener('click', (e) => {
     e.preventDefault(); // prevent default any way

     const self = this;

     call_returning_promise()
          .then(res => {
             if(res) {
               window.location.replace( self.href );
             }
          });
});

You can for sure make the above flow [look] synchronous by using async-await

Sumit Wadhwa
  • 2,825
  • 1
  • 20
  • 34
0

you can use this after "preventDefault" method

//Here evt.target return default event (eg : defult url etc)

var defaultEvent=evt.target;

//Here we save default event ..

if("true")
{
//activate default event..
location.href(defaultEvent);
}
0

You can always use this attached to some click event in your script:

location.href = this.href;

example of usage is:

jQuery('a').click(function(e) {
    location.href = this.href;
});
kkatusic
  • 119
  • 1
  • 8
0

Considering the prevously accepted answers, both unbind and click events are deprecated and it should be replaced with off and trigger.

 $(this).off('submit').trigger('submit');
AzizStark
  • 1,390
  • 1
  • 17
  • 27
-1

this code worked for me to re-instantiate the event after i had used :

event.preventDefault(); to disable the event.


event.preventDefault = false;
LCMr_music
  • 37
  • 4
-2

I have used the following code. It works fine for me.

$('a').bind('click', function(e) {
  e.stopPropagation();
});
  • 2
    [As explained in the jQuery API documentation](http://api.jquery.com/event.stoppropagation/), this prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. That's not the same as/or the opposite of `event.preventDefault()`; – ᴍᴀᴛᴛ ʙᴀᴋᴇʀ Jan 20 '15 at 14:53
  • 3
    This isn't what the question asked either. – Matt Fletcher Sep 21 '16 at 12:57