What is the opposite of evt.preventDefault();

JavascriptJqueryPreventdefault

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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:

https://stackoverflow.com/questions/1551389/how-to-enable-default-after-event-preventdefault#1556696

https://stackoverflow.com/questions/1164132/how-to-reenable-event-preventdefault/1164177#1164177

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()
});

Solution 2 - Javascript

function(evt) {evt.preventDefault();}

and its opposite

function(evt) {return true;}

cheers!

Solution 3 - Javascript

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

Solution 4 - Javascript

OK ! it works for the click event :

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

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

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

});

Solution 5 - Javascript

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

Solution 6 - Javascript

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();
    });
});

Solution 7 - Javascript

Solution 8 - Javascript

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/

Solution 9 - Javascript

This is what I used to set it:

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

And to undo it:

$("body").unbind("touchmove");

Solution 10 - Javascript

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.

Solution 11 - Javascript

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: https://developer.mozilla.org/en/DOM/document.createEvent">document.createEvent</a>


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

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

$('#foo').trigger('click');

Solution 12 - Javascript

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();
}

Solution 13 - Javascript

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

});

Solution 14 - Javascript

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..

Solution 15 - Javascript

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

Solution 16 - Javascript

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

Solution 17 - Javascript

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 synchronous by using async-await

Solution 18 - Javascript

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

event.preventDefault(); to disable the event.


event.preventDefault = false;

Solution 19 - Javascript

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

$('a').bind('click', function(e) {
  e.stopPropagation();
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBryanView Question on Stackoverflow
Solution 1 - JavascriptGrant ThomasView Answer on Stackoverflow
Solution 2 - JavascriptfoxybaggaView Answer on Stackoverflow
Solution 3 - JavascriptBradley FloodView Answer on Stackoverflow
Solution 4 - JavascriptSNS WebView Answer on Stackoverflow
Solution 5 - Javascriptuser10625817View Answer on Stackoverflow
Solution 6 - JavascriptBobby PearsonView Answer on Stackoverflow
Solution 7 - JavascriptRafael XavierView Answer on Stackoverflow
Solution 8 - Javascriptkarim79View Answer on Stackoverflow
Solution 9 - JavascriptJoe McLeanView Answer on Stackoverflow
Solution 10 - JavascriptParthaView Answer on Stackoverflow
Solution 11 - JavascriptGary GreenView Answer on Stackoverflow
Solution 12 - JavascriptRazaView Answer on Stackoverflow
Solution 13 - JavascriptPeck_conyonView Answer on Stackoverflow
Solution 14 - Javascripthonk31View Answer on Stackoverflow
Solution 15 - Javascriptuser3631514View Answer on Stackoverflow
Solution 16 - JavascriptkkatusicView Answer on Stackoverflow
Solution 17 - JavascriptSumit WadhwaView Answer on Stackoverflow
Solution 18 - JavascriptLCMr_musicView Answer on Stackoverflow
Solution 19 - JavascriptVeeraPrasadView Answer on Stackoverflow