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

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

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

function(evt) {evt.preventDefault();}
and its opposite
function(evt) {return true;}
cheers!

To process a command before continue a link from a click event in jQuery:
Eg: Click me
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();

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

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

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 what I used to set it:
$("body").on('touchmove', function(e){
e.preventDefault();
});
And to undo it:
$("body").unbind("touchmove");

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.

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

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

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

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

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

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

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

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

this code worked for me to re-instantiate the event after i had used :
event.preventDefault(); to disable the event.
event.preventDefault = false;

I have used the following code. It works fine for me.
$('a').bind('click', function(e) {
e.stopPropagation();
});

Related

preventDefault in function with more parameters?

I have a function that is run when clicking an input in the DOM. I want to stop the element from being checked until my function can approve it. I'm trying to do this using e.preventDefault(); or event.preventDefault(); (is there any difference?!) but I'm not succeeding, what am I doing wrong?
This is my code without the preventDefault-part.
$(document).on("click","[data-item]", function() {
cart.updateCart(this);
});
cart.updateCart = function(target) {
// do stuff and perhaps check the input element
}
I tried this, which is not working:
$(document).on("click","[data-item]", function() {
cart.updateCart(this, event);
});
cart.updateCart = function(target, event) {
event.preventDefault();
console.log(event); // returns MouseEvent -- is this even the correct "event" ?
// do stuff and perhaps check the input element
}
I think I'm not "getting" how this works. Perhaps someone can explain how this works and what I'm doing wrong?
event should be the first parameter passed into your click handler. So your code really should be like this.:
$(document).on("click","[data-item]", function(event) {
cart.updateCart(this, event);
});
cart.updateCart = function(target, event) {
event.preventDefault();
console.log(event); // returns MouseEvent -- is this even the correct "event" ?
// do stuff and perhaps check the input element
}
You can read more about preventing default actions here.

Getting result of Confirm dialog on Cancel Button in jQuery event hander

On one side I have a form with submit/cancel buttons and the cancel has an onclick event (to do some cleanup) that is wrapped in a standard confirm dialog. All standard stuff.
But then I have a second script (and it MUST be a second script) that may only sometimes be loaded, that needs to add more tasks if the form is cancelled. So - I can listen for the onclick...
$( "#cancelBtn" ).on( "click", function(a) {
// do more stuff...
});
but I only want to 'do more stuff' if the confirm around the onclick is OK. I am probably missing something stupidly simple but I have been at this all day and am about to give up! Can anyone point me in the right direction?
Update: I can not change the form onclick code - it has to stay separate and as it now is.... so the confirm has to stay where it is.
Do it like this:
$( "#cancelBtn" ).on( "click", function(a) {
if (confirm('Are you sure you want to cancel?')) { // Standard confirmation message.
// Pressed OK.
// do more stuff...
} else {
// Pressed Cancel.
}
});
Hope this helps.
EDIT: Since you can't change the script performing form duty, a solution would be to overwrite the confirm()-function:
var _confirm = window.confirm;
window.confirm = function() {
//catch result
var confirmed = _confirm.apply(window,arguments);
if (confirmed) {
//confirm ok, do some tasks
} else {
//confirm cancelled, do some cleanup
}
//pass result on to the caller
return confirmed;
};
http://jsfiddle.net/sofcuoab/
put the tasks in the second script in
function doMoreStuff(){
//more tasks
}
and call it in your confirm-clause like this
if (typeof doMoreStuff === "function") {
doMoreStuff();
}
or like this
try {
doMoreStuff();
}
catch(err) {
//no second script loaded
}

prevent jQuery post request executed twice by double click

I've searched for equal questions, but found not a single one for my specific case.
I have an element
<span id="myButton">Click</span>
and a jQuery post-request bound to it
$(document).ready( function()
{
$(document).on( 'click', '#myButton', function(e)
{
$.post( "RESPONDING_WEBPAGE_HERE.php" ).done( function( result )
{
console.log( result );
});
});
});
Now, for every time you click the button, it makes a post-request. Makes sense. What I want is a good solution for only executing the post-request, if the result function (.done()) is executed.
For sure, I know to handle that with a variable like var isAjaxRequest = false; setting it to true, and back to false in the resulting function, but maybe there is a better (jQuery build-in) way of doing it.
Here is my solution by now. I would be really great if there are better ones.
var isAjaxRequest = false;
$(document).ready( function()
{
$(document).on( 'click', '#myButton', function(e)
{
if( !isAjaxRequest )
{
isAjaxRequest = true;
$.post( "RESPONDING_WEBPAGE_HERE.php" ).done( function( result )
{
isAjaxRequest = false;
console.log( result );
});
}
});
});
Thank you =)
I commonly set the button to disabled when it is clicked and then remove the disabled attribute on the callbacks for the POST request.
$(document).on('click', '#button', function () {
$('#button').attr('disabled', true);
$.post('something').done(function () {
$('#button').removeAttr('disabled');
}).fail(function () {
$('#button').removeAttr('disabled');
});
});
This will prevent the button from being clicked again once it has already been clicked.
As per the comments; If you want this behaviour on a span element or others which don't allow the disabled attribute, you could set a class when clicked.
$(document).on('click', 'span#button:not(.disabled)', function () {
$(this).addClass('disabled');
$.post('something').done(function () {
$(this).removeClass('disabled');
}).fail(function () {
$(this).removeClass('disabled');
});
});
The above code will make sure the element can only be clicked if it doesn't have the disabled class. This will also work for the button elements so there is no need to duplicate code for both methods.
I like to use .one() to attach the event handler and re-attach the event after the ajax call is complete. This will handle all cases even when your target doesn't support disabling:
//define handler function
var myButtonHandler = function(e) {
$.post("RESPONDING_WEBPAGE_HERE.php").done(function() {
attachButtonHandler("#mybutton"); //re-attach the click event after AJAX complete
});
}
//attach an event handler that's only good for one click
function attachButtonHandler(selector) {
$(document).one('click', selector, myButtonHandler);
}
//on doc ready, attach the event handler for the first time
$(function() {
attachButtonHandler("#mybutton");
});

Intercept clicks, make some calls then resume what the click should have done before

Good day all, I have this task to do:
there are many, many many webpages, with any kind of element inside, should be inputs, buttons, links, checkboxes and so on, some time there should be a javascript that could handle the element behaviour, sometimes it is a simple ... link.
i have made a little javascript that intercepts all the clicks on clickable elements:
$( document ).ready(function() {
$('input[type=button], input[type=submit], input[type=checkbox], button, a').bind('click', function(evt, check) {
if (typeof check == 'undefined'){
evt.preventDefault();
console.log("id:"+ evt.target.id+", class:"+evt.target.class+", name:"+evt.target.name);
console.log (check);
$(evt.target).trigger('click', 'check');
}
});
});
the logic is: when something is cllicked, I intercept it, preventDefault it, make my track calls and then resme the click by trigger an event with an additional parameter that will not trigger the track call again.
but this is not working so good. submit clicks seams to work, but for example clicking on a checkbox will check it, but then it cannot be unchecked, links are simply ignored, I track them (in console.log() ) but then the page stay there, nothing happens.
maybe I have guessed it in the wrong way... maybe i should make my track calls and then bind a return true with something like (//...track call...//).done(return true); or something...
anyone has some suggestions?
If you really wanted to wait with the click event until you finished with your tracking call, you could probably do something like this. Here's an example for a link, but should be the same for other elements. The click event in this example fires after 2seconds, but in your case link.click() would be in the done() method of the ajax object.
google
var handled = {};
$("#myl").on('click', function(e) {
var link = $(this)[0];
if(!handled[link['id']]) {
handled[link['id']] = true;
e.preventDefault();
e.stopPropagation();
//simulate async ajax call
window.setTimeout(function() {link.click();}, 2000);
} else {
//reset
handled[link['id']] = false;
}
});
EDIT
So, for your example, this would look something like this
var handled = {};
$( document ).ready(function() {
$('input[type=button], input[type=submit], input[type=checkbox], button, a').bind('click', function(evt) {
if(!handled[evt.target.id]) {
handled[evt.target.id] = true;
evt.preventDefault();
evt.stopPropagation();
$.ajax({
url: 'your URL',
data: {"id" : evt.target.id, "class": evt.target.class, "name": evt.target.name},
done: function() {
evt.target.click();
}
});
} else {
handled[evt.target.id] = false;
}
});

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

jquery toggle calls preventDefault() by default, so the defaults don't work.
you can't click a checkbox, you cant click a link etc etc
is it possible to restore the default handler?
In my case:
$('#some_link').click(function(event){
event.preventDefault();
});
$('#some_link').unbind('click'); worked as the only method to restore the default action.
As seen over here: https://stackoverflow.com/a/1673570/211514
Its fairly simple
Lets suppose you do something like
document.ontouchmove = function(e){ e.preventDefault(); }
now to revert it to the original situation, do the below...
document.ontouchmove = function(e){ return true; }
From this website.
It is not possible to restore a preventDefault() but what you can do is trick it :)
<div id="t1">Toggle</div>
<script type="javascript">
$('#t1').click(function (e){
if($(this).hasClass('prevented')){
e.preventDefault();
$(this).removeClass('prevented');
}else{
$(this).addClass('prevented');
}
});
</script>
If you want to go a step further you can even use the trigger button to trigger an event.
function DoPrevent(e) {
e.preventDefault();
e.stopPropagation();
}
// Bind:
$(element).on('click', DoPrevent);
// UnBind:
$(element).off('click', DoPrevent);
in some cases* you can initially return false instead of e.preventDefault(), then when you want to restore the default to return true.
*Meaning when you don't mind the event bubbling and you don't use the e.stopPropagation() together with e.preventDefault()
Also see similar question (also in stack Overflow)
or in the case of checkbox you can have something like:
$(element).toggle(function(){
$(":checkbox").attr('disabled', true);
},
function(){
$(":checkbox").removeAttr('disabled');
})
You can restore the default action (if it is a HREF follow) by doing this:
window.location = $(this).attr('href');
if it is a link then $(this).unbind("click"); would re-enable the link clicking and the default behavior would be restored.
I have created a demo JS fiddle to demonstrate how this works:
Here is the code of the JS fiddle:
HTML:
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
Default click action is prevented, only on the third click it would be enabled
<div id="log"></div>
Javascript:
<script>
var counter = 1;
$(document).ready(function(){
$( "a" ).click(function( event ) {
event.preventDefault();
$( "<div>" )
.append( "default " + event.type + " prevented "+counter )
.appendTo( "#log" );
if(counter == 2)
{
$( "<div>" )
.append( "now enable click" )
.appendTo( "#log" );
$(this).unbind("click");//-----this code unbinds the e.preventDefault() and restores the link clicking behavior
}
else
{
$( "<div>" )
.append( "still disabled" )
.appendTo( "#log" );
}
counter++;
});
});
</script>
Test this code, I think solve your problem:
event.stopPropagation();
Reference
The best way to do this by using namespace. It is a safe and secure way. Here .rb is the namespace which ensures unbind function works on that particular keydown but not on others.
$(document).bind('keydown.rb','Ctrl+r',function(e){
e.stopImmediatePropagation();
return false;
});
$(document).unbind('keydown.rb');
ref1: http://idodev.co.uk/2014/01/safely-binding-to-events-using-namespaces-in-jquery/
ref2: http://jqfundamentals.com/chapter/events
If the element only has one handler, then simply use jQuery unbind.
$("#element").unbind();
Disable:
document.ontouchstart = function(e){ e.preventDefault(); }
Enable:
document.ontouchstart = function(e){ return true; }
The Event interface's preventDefault() method 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. The event continues to propagate as usual, unless one of its event listeners calls stopPropagation() or stopImmediatePropagation(), either of which terminates propagation at once.
Calling preventDefault() during any stage of event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur.
You can use Event.cancelable to check if the event is cancelable. Calling preventDefault() for a non-cancelable event has no effect.
window.onKeydown = event => {
/*
if the control button is pressed, the event.ctrKey
will be the value [true]
*/
if (event.ctrKey && event.keyCode == 83) {
event.preventDefault();
// you function in here.
}
}
I had a problem where I needed the default action only after some custom action (enable otherwise disabled input fields on a form) had concluded. I wrapped the default action (submit()) into an own, recursive function (dosubmit()).
var prevdef=true;
var dosubmit=function(){
if(prevdef==true){
//here we can do something else first//
prevdef=false;
dosubmit();
}
else{
$(this).submit();//which was the default action
}
};
$('input#somebutton').click(function(){dosubmit()});
Use a boolean:
let prevent_touch = true;
document.documentElement.addEventListener('touchmove', touchMove, false);
function touchMove(event) {
if (prevent_touch) event.preventDefault();
}
I use this in a Progressive Web App to prevent scrolling/zooming on some 'pages' while allowing on others.
You can set to form 2 classes. After you set your JS script to one of them, when you want to disable your script, you just delete the class with binded script from this form.
HTML:
<form class="form-create-container form-create"> </form>
JS
$(document).on('submit', '.form-create', function(){
..... ..... .....
$('.form-create-container').removeClass('form-create').submit();
});
in javacript you can simply like this
const form = document.getElementById('form');
form.addEventListener('submit', function(event){
event.preventDefault();
const fromdate = document.getElementById('fromdate').value;
const todate = document.getElementById('todate').value;
if(Number(fromdate) >= Number(todate)) {
alert('Invalid Date. please check and try again!');
}else{
event.currentTarget.submit();
}
});
Worked as the only method to restore the default action.
$('#some_link').unbind();
This should work:
$('#myform').on('submit',function(e){
if($(".field").val()==''){
e.preventDefault();
}
});
$('#my_elementtt').click(function(event){
trigger('click');
});
I'm not sure you're what you mean: but here's a solution for a similar (and possibly the same) problem...
I often use preventDefault() to intercept items. However: it's not the only method of interception... often you may just want a "question" following which behaviour continues as before, or stops.
In a recent case I used the following solution:
$("#content").on('click', '#replace', (function(event){
return confirm('Are you sure you want to do that?')
}));
Basically, the "prevent default" is meant to intercept and do something else: the "confirm" is designed for use in ... well - confirming!

Categories

Resources