Double click prevented but prevent default does not work - javascript

I am using code from this post and the double click prevention works, however the button still does not respond to preventDefault
Can anyone lend a hand please?
js:
var myBtn = $('.myLink');
var handler = function(e){
e.preventDefault();
console.log("prevent 2x click");
$(this).unbind('click');
setTimeout(function(){ myBtn.click(handler); }, 500);
}
myBtn.click(handler);
html:
<a class='myLink' href="#">my link to click</a>

Reason is that when you unbind the handler(which has preventDefault) and in the small period of time one more click comes in it doesn't prevent the default behavior. So you can attach a dedicated handler to prevent default and unbind the handler that just does your other logic. Try this way:
var myBtn = $('.myLink');
var handler = function(e){
$(this).unbind('click', handler); //unbind only your handler
setTimeout(function(){
myBtn.click(handler); }
, 500);
}
myBtn.click(preventDefault); //have this bound to the anchor to prevent the default behavior always
myBtn.click(handler);
function preventDefault(e){
e.preventDefault();
}
Demo

Related

reenable onclick behavior after preventDefault

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

Capturing an event with jquery

I got a double event to manage. The two events are both "click" and they're handled with jquery. The html is the following:
<div class="siteMap" style="width:23%;">
<h5>Divisione Anticontraffazione</h5>
<span class="menufooter">
<span class="link1">Introduzione</span><br>
<span class="link2">Filosofia</span><br>
<span class="link3">Negozio online</span></span><br>
</div>
Then i have my click events which fires inside the menufooter span and inside every single link span. The code is like this:
$(document).ready(function() {
$('span.menufooter').click(function() {
//my code here
});
$("span.link1").click(function() {
//my code here
});
});
I need an event capturing action, the click on the span menufooter has to fire the event before the click on the span link1 fires. At this point, none of the two events is firing. Any hint?
How about only fire event on .menufooter
$(document).ready(function() {
$('span.menufooter').click(function(e) {
//my code here 1
// Capture Event Propagation
if ( $("span .link1").find(e.target).length>0 ){
//my code here 2
};
});
});
http://jsfiddle.net/9QLtG/
You could prevent the click from bubbling, and then trigger the click on the parent element so whatever is in that handler executes first (unless it's async)
$(document).ready(function () {
$('.menufooter').click(function () {
// fires before ....
});
$("span.link1").click(function (e) {
e.stopPropagation();
$('.menufooter').trigger('click');
// .... this fires, as it's triggered above
});
});
FIDDLE
I would have 1 click listener that listens to the wrapper. You can check the event's target to see if they actually clicked on a link and run code accordingly.
For example:
$(document).ready(function() {
$('.container').click(function(e) {
// Perform action when they clicked in the main wrapper,
// regardless of whether or not it was a link.
console.log("I clicked in the wrapper...");
if ($(e.target).hasClass('link')) {
// Perform action if they clicked on a link.
console.log("...but more specifically, on a link.");
}
});
});
Here's a fiddle that demonstrates this: http://jsfiddle.net/WaYFr/
Try this event.stopPropagation();
$("span.link1").click(function(event) {
event.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