[javascript] What is the opposite of evt.preventDefault();

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

This question is related to javascript jquery preventdefault

The answer is


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 !

});

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

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

and its opposite

function(evt) {return true;}

cheers!


This is what I used to set it:

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

And to undo it:

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

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>

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.


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


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

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/


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

});

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

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

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

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

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

event.preventDefault(); to disable the event.


event.preventDefault = false;

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

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


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

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


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to preventdefault

React onClick and preventDefault() link refresh/redirect? Bootstrap 3 - disable navbar collapse How to preventDefault on anchor tags? Stop form from submitting , Using Jquery Prevent Default on Form Submit jQuery What's the difference between event.stopPropagation and event.preventDefault? What is the opposite of evt.preventDefault(); How to unbind a listener that is calling event.preventDefault() (using jQuery)? event.preventDefault() function not working in IE