reenable onclick behavior after preventDefault - javascript

If I disable a click event on my element in one point how can I later can re-enable again?
$(myElem).click(function(event) {
event.preventDefault();
});

Html:
<button id="test" >test</button>
Js:
$('#test1').click(function (e){
if($(this).hasClass('prevented')){
e.preventDefault();
}
});
You can also use eg. data-attribute.

I dont know, if this is the best solution, but its an easy one: set a flag outside the "click scope" ...
var pd = true;
$(myElem).click(function (event) {
if (pd) event.preventDefault();
// other actions
});
Then you could later set pd = false. If pd is defined outside the click handler, this should work in my opinion.

$(myElem).click(function (event) { event.preventDefault(); });
$(myElem).unbind('click');

Related

html div onclick event

I have one html div on my jsp page, on that i have put one anchor tag, please find code below for that,
<div class="expandable-panel-heading">
<h2>
<a id="ancherComplaint" href="#addComplaint"
onclick="markActiveLink(this);">ABC</a>
</h2>
</div>
js code
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
function markActiveLink(el) {
alert($(el).attr("id"));
}
here I when I click on div I got alert with 123 message, its fine but when I click on ABC I want message I want to call markActiveLink method.
JSFiddle
what is wrong with my code? please help me out.
The problem was that clicking the anchor still triggered a click in your <div>. That's called "event bubbling".
In fact, there are multiple solutions:
Checking in the DIV click event handler whether the actual target element was the anchor
→ jsFiddle
$('.expandable-panel-heading').click(function (evt) {
if (evt.target.tagName != "A") {
alert('123');
}
// Also possible if conditions:
// - evt.target.id != "ancherComplaint"
// - !$(evt.target).is("#ancherComplaint")
});
$("#ancherComplaint").click(function () {
alert($(this).attr("id"));
});
Stopping the event propagation from the anchor click listener
→ jsFiddle
$("#ancherComplaint").click(function (evt) {
evt.stopPropagation();
alert($(this).attr("id"));
});
As you may have noticed, I have removed the following selector part from my examples:
:not(#ancherComplaint)
This was unnecessary because there is no element with the class .expandable-panel-heading which also have #ancherComplaint as its ID.
I assume that you wanted to suppress the event for the anchor. That cannot work in that manner because both selectors (yours and mine) select the exact same DIV. The selector has no influence on the listener when it is called; it only sets the list of elements to which the listeners should be registered. Since this list is the same in both versions, there exists no difference.
Try this
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
$('#ancherComplaint').click(function (event) {
alert($(this).attr("id"));
event.stopPropagation()
})
DEMO
Try following :
$('.expandable-panel-heading').click(function (e) {
if(e.target.nodeName == 'A'){
markActiveLink(e.target)
return;
}else{
alert('123');
}
});
function markActiveLink(el) {
alert($(el).attr("id"));
}
Here is the working demo : http://jsfiddle.net/JVrNc/4/
Change your jQuery code with this. It will alert the id of the a.
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
markActiveLink();
alert('123');
});
function markActiveLink(el) {
var el = $('a').attr("id")
alert(el);
}
Demo
You need to read up on event bubbling and for sure remove inline event handling if you have jQuery anyway
Test the click on the div and examine the target
Live Demo
$(".expandable-panel-heading").on("click",function (e) {
if (e.target.id =="ancherComplaint") { // or test the tag
e.preventDefault(); // or e.stopPropagation()
markActiveLink(e.target);
}
else alert('123');
});
function markActiveLink(el) {
alert(el.id);
}
I would have used stopPropagation like this:
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
$('#ancherComplaint').on('click',function(e){
e.stopPropagation();
alert('hiiiiiiiiii');
});
Try out this example, the onclick is still called from your HTML, and event bubbling is stopped.
<div class="expandable-panel-heading">
<h2>
<a id="ancherComplaint" href="#addComplaint" onclick="markActiveLink(this);event.stopPropagation();">ABC</a>
</h2>
</div>
http://jsfiddle.net/NXML7/1/
put your jquery function inside ready function for call click event:
$(document).ready(function() {
$("#ancherComplaint").click(function () {
alert($(this).attr("id"));
});
});
when click on div alert key
$(document).delegate(".searchbtn", "click", function() {
var key=$.trim($('#txtkey').val());
alert(key);
});

What is the opposite of evt.preventDefault();

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

Disable onbeforeunload for links

How can I disable onbeforeunload for links?
var show = true;
function showWindow(){
if(show){
alert('Hi');
return "Hi Again";
}
}
$('a').click(function(){
show = false;
});
window.onbeforeunload = showWindow;
This is what I have, but it still shows when I click on an 'a' element
Button code:
<button type="submit" class="submitBtn"><span>Open Account</span></button>
Instead of
show = false;
try
window.onbeforeunload = null;
This will simply unbind the function from the event.
I just ran into the same problem and found a very easy solution:
$("a").mousedown(function() {
$(window).unbind();
});
This will remove the onbeforeunload event just before the click event is triggered.
Use following code to unbind the event:
javascript:window.onbeforeunload=function(){null}
For some reason, using window.onbeforeunload = null did not work for me.
What did the trick instead was adding and removing the listener accordingly:
let onBeforeUnloadListener;
// Mounting
window.addEventListener('beforeunload', onBeforeUnloadListener = ev => {
ev.preventDefault();
ev.returnValue = 'Any';
});
// Unmounting
window.removeEventListener('beforeunload', onBeforeUnloadListener);
This idea came to mind due to using getEventListeners(window), which shown the active beforeunload listeners.

How to stop onclick event in div from propagating to the document?

I want to stop propagation of this div's onclick event to the document? When the user click on the "div", both alerts appear: 1) the div's alert and 2) the document's alert. I want to suppress the document alert.
I know how to do it using addEventListener, but is there another way to to do it? The problem below is that I don't know how to get ahold of the event -- I tried "event = element.onclick", shown below, but that doesn't work. How do I get the event?
<head>
<script>
function showMenu(element) {
alert("div clicked");
event = element.onclick; // HOW TO GET HOLD OF THE EVENT?
// Don't propogate the event to the document
if (event.stopPropagation) {
event.stopPropagation(); // W3C model
} else {
event.cancelBubble = true; // IE model
}
}
document.onclick = function() {
alert('document clicked');
};
</script>
</head>
<body>
<div id="foodmenu" onclick="showMenu(this);">Click inside this div</div>
or click outside the div.
</body>
Change your function definition to include the event:
function showMenu(event, element) {
alert("div clicked");
// Don't propogate the event to the document
if (event.stopPropagation) {
event.stopPropagation(); // W3C model
} else {
event.cancelBubble = true; // IE model
}
}
Then change the call to pass in the event:
div id="fooddmenu" onclick="showMenu(event, this);">Click inside this div</div>
Try EventListeners:
html:
<div id="fooddmenu">Click inside this div</div>or click outside the div.​​​​​​​​​​
js:
function showMenu(e) {
alert("div clicked");
}
document.onclick = function() {
alert('document clicked');
};
window.onload = function(){
document.getElementById("fooddmenu").addEventListener("click", function(e){
showMenu(this);
e.stopPropagation();
});
};
Add the onclick to the body element.
Douglas,
It does stop the event from getting bubbled up.
Check this out http://jsbin.com/ahoyi/edit
here, if you comment the alert statement, it will show 2 alerts on clicking the smaller box else only one.
Hope this helps.
well, that's a jquery code.
$("#id") same as document.getElementById("id")
.click function is same as addEvent("click", function() { ... } );
so basically both the functions there are click handlers for Parent and Child DIVs.
Observe the output by commenting / uncommenting the "return false;" statement.
Hope that helps.
By the way, sorry for that "$" confusion.
$("div").click(function(){
...
...
...
return false; //this will stop the further propagation of the event
});
Add Pointer-events: none to the particular element will help to stop pointer events.
event.StopPropagation() will help us to avoid child propagating

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