JavaScript suppress double click selection - javascript

i'm working on a slide gallery at the moment.
My problem is that when i click the navigation divs very fast, the browsers default behavior is fired (selection of content).
My question is: how can I suppress the default double click behavior?
navigationDiv.onclick = function () {
// do something
};
A jQuery solution would also be suitable since i'm using it.
Thanks in advance!

$("yourselector").dblclick(function(){
return false;
});
You can also use event.preventDefault()
$("yourselector").dblclick(function(event){
event.preventDefault();
});

Just FYI, in Firefox and Safari/Chrome, selection can be disabled through CSS, too:
.navigationDiv {
-moz-user-select: none;
-webkit-user-select: none;
}
I think this is more simple when your purpose is only to prevent selections from taking place on a certain element.

You could try disabling the onselectstart event of the target element.
navigationDiv.onselectstart=function(){return false}
Not sure if this is x-browser compatible. (I'll check it)
Edit
Turns out that this is a IE-only event. To accomplish the same in Mozilla, you would have to disable the -moz-user-select CSS style. In JavaScript that would be:
navigationDiv.style.MozUserSelect="none"
To be honest, I think you would be better off disabling the double-click event, as described in the other comments here.

Putting a return false; at the end of the event handler should be able to suppress the default selection behaviour.

Calling event.preventDefault() in dblclick handler will help only if it is called in the element BEING CLICKED, not in the parent's event handler.
In scenarios when there's a container with multiple children, default behaviour of double click will happen in a child and bubbled up to it's parent. In this case there're 2 options:
Clear selection in parent's event handler, e.g.:
window.getSelection().empty(). The issue with this approach is that you'll notice blinking of the selected text and in Opera there'll be a pop-up ('Copy', 'Search').
Traverse all children and call e.PreventDefault() in their dblclick.

You could try making the "dblclick" event return false?
$('.someStuff').bind('dblclick', function() { return false; });

Cancel the ondblclick event:
navigationDiv.ondblclick = function () {
return false; // cancel default
};
http://www.quirksmode.org/js/events_mouse.html

Quite Simple:
navigationDiv.ondblclick = function (event) {
// do something
if (!event) event = window.event;
if (event.preventDefault)
event.preventDefault();
else
event.returnValue = false;
};
This works on IE and Mozilla browsers.

Neither e.preventDefault() nor return false ensure in all cases, that double-click's default action (text selection) will not happen. But, having read this note and this answer I've composed a working solution for a similar problem of my own:
$(...your selector...)
.on('mousedown',function(e){ if (e.detail>1) return false }) // prevent dblclick default
.on('dblclick', ...your dblclick handler...);

Related

Overwriting tap event with preventDefault

I had a lot of:
$('#element').on('tap', function(){
// some code ..
})
I searched many questions about the tap event problem firing twice, and I solved my problem using e.preventDefault(), now I have a lot of:
$('#element').on('tap', function(e){
e.preventDefault();
// some code ..
})
Ok, but as I said, I have many of these calls and I don't like much to write every time e.preventDefault(), then I typed $.fn.tap on chrome's console and it showed me:
function (a){return a?this.bind(c,a):this.trigger(c)}
I tried to overwrite it this way:
$.fn.tap = function (a) {
a.preventDefault();
return a?this.bind(c,a):this.trigger(c)
}
But it didn't worked as it did in the previous e.preventDefault().
I'm not seeing anything obvious and I'm out of ideas for this.
Any help or idea is appreciated. Thanks in advance.
This is how you can create your $.fn.tap:-
$.fn.tap = function(f) {
$(this).on('tap', function(e) {
e.preventDefault();
f();
});
return this;
};
//usage
$('.selector').tap(function() {
alert('foo bar')
})
#Washington Guedes - overwrite the default tap-event to always use e.preventDefault()
rather than changing from $(element).on('tap', function(){}) to
$(element).tap(function(){})
You could add a delegate event to body for tap, without specifying a target. This will then fire for all tap events on the body, which you can then check if the target has its own tap event, so you can then e.preventDefault();.
NOTE: This will not work for delegated tap events as shown.
// global tap handler
$('body').on('tap', function(e) {
if ($._data(e.target, "events").tap)
e.preventDefault();
});
// tap event
$('a.tap').on('tap', function(e) {
$(this).css('color', 'red');
});
// delegated tap event
$('body').on('tap', 'a.delegate', function(e) {
$(this).css('color', 'green');
});
a {
display: block;
margin: 20px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"></script>
<a class="tap" href="www.google.co.uk">tap event, prevented.</a>
<a class="delegate" href="www.google.co.uk">delegate tap event, not prevented.</a>
no tap event, not prevented
One of the cool features of jQuery (I usually don't use 'jQuery' and 'cool' in a single sentence) is that it lets you specify custom behaviour for events, using the $.event.special object.
There is very little documentation on the subject, so a little example would be in order.
A working fiddle using the click event (as this was more convenient for me to write on my laptop) can be found here
Translated to your request to have all tap events have e.preventDefault() invoked before the actual handler, would look like:
$.event.special.tap.add = function(options) {
var handler = options.handler;
options.handler = function(e) {
e.preventDefault();
return handler.apply(this, arguments);
}
}
What this code does (should do, as I haven't actually tested the tap version above) is telling jQuery that you want a special treatment for the tab event, more particularly you want to provide a 'wrapping handler' which does nothing more than call e.preventDefault() before calling the provided event handler.
UPDATE: prevented the default tap-settings from being overwritten, for future visitors
NOTE: Before you make any attempt on changing the default behaviour of things, you should ask yourself why the defaults don't work for you. Mostly because changing default (=expected) behaviour will upset your future self (or worse, another person) while maintaining your code and adding features.
In order to create a maintainable (and predictable) flow in your code the suggested solution to create a special case function ($.fn.tap) is in fact a very viable solution, as it does not interfere with the default (=expected) behaviour of things.
From the links I provided you should also be able to create your own event type (e.g. tapOnly) and make it more obvious there is some custom work involved. Then again, both of these solutions will require you to change your event bindings, which is what you are trying to prevent.
I knew can be a bad idea but I've just tested this in Chrome
$('*').on('tap',function(e){
e.preventDefault();
});
$('#element').on('tap', function(){
// some code ..
});
and if you don't need this for all elements:
$('*').not('#aCertainElement').on('tap',function(e){
e.preventDefault();
});
I had a similar problem, in which e.preventDefault() would work on some cases, but not on others. It showed no errors, and using try-catch was not displaying the catch alert. Adding e.stopImmediatePropagation() did the trick, in case it helps anyone

Stop propagation doesn't work

I have the below JQuery eventhandler. I want to stop all navigations on a web page.
$(document).click(function(event) {
event.stopPropagation();
event.preventDefault();
event.cancelBubble = true;
event.stopImmediatePropagation();
$(document).css('border-color','');
$(document).css('background-color','');
$(event.target).css('border-color','yellow');
$(event.target).css('background-color','#6BFF70');
return false;
});
When I use this on Facebook Login page, it stops all navigations. But in Google home page, "I'm Feeling Lucky" button still navigates to next page. How do I avoid it?
I'm using JavaFX browser by the way. It is similar to Safari browser.
If I load the Google search page, and execute this at the console:
document.body.addEventListener(
"click",
function (ev) { ev.stopPropagation(); ev.preventDefault(); },
true);
then I cannot click the "I'm Feeling Lucky" button anymore. The key is to use the third parameter and set it to true. Here is what MDN [says] about it:
useCapture Optional
If true, useCapture indicates that the user wishes to initiate capture. After initiating capture, all events of the specified type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree.
(Emphasis added.)
What you tried to do does not work because your event handler is on document, and thus will be called after any event handlers on the children of the document. So your handler cannot prevent anything.
With useCapture set to true, you can operate on the event before it gets a chance to be passed to the child element. I do not know of a way to have jQuery's event handlers work in the way you get with useCapture. Barmar's answer here says you can't use jQuery to set such handler. I'm inclined to believe him.
99.99% of webpages won't be able to have their navigation stopped by stopping event propagation for the reason I commented (you can't stop the event before it triggers all handlers for the initial target of the event). If preventing navigation is all you are interested in, I recommend using the window.onbeforeunload event, which is made for this exact situation.
Here is an example: http://jsfiddle.net/ejreseuu/
HTML:
google
JS:
window.onbeforeunload = function() {
return "Are you sure?"
}
There is no way to not have a confirmation box that I know of, as code that locks the user out of navigating away no matter what they do is generally malicious.
preventDefault() should not work in this case, cause Google relied on custom event listeners to handle click events on this button. While preventDefault()
prevents browser's default behavior.
For example, if this button was of type="submit", preventing default on click event would prevent browser's default behavior, which is submitting a form. But in this case click is handled by eventListeners added to the button itself. preventDefault() won't affect catching an event by them. Nor stopPropagation(), because it stops propagation of event to higher levels of DOM, while other eventListeners on the same level (button in our case) still get the event. stopImmediatePropagation() could work in theory, but only if your eventListener was added before google's.
So the easiest way to stop propagation is to stop an event before it reaches button node, and that's on capture phase, because button is the lowest element in the hierarchy. This can be done by passing true argument while adding eventListener
document.body.addEventListener("click", function (event) {
event.stopPropagation();
}, true);
This way event will be stopped before bubble phase, and so before it reaches eventListeners added to the button. More on capture and bubble phases here
Note that preventDefault() is not needed in this case. Actually, this button's event listeners are to prevent default themselves. Here are those eventListeners, for click and keyup respectively:
d = function(a) {
c.Xa.search(c.yc(), b);
return s_1vb(a)
}
function(a) {
13 != a.keyCode && 32 != a.keyCode || d(a)
}
note call to s_1vb, here is its sourse:
s_1vb.toString();
/*"function (a){
a&&(a.preventDefault&&a.preventDefault(),a.returnValue=!1);
return!1
}"*/
Basically its a function that take an event and do everything possible to prevent browser's default behavior
By the way, default behavior can be canceled on any stage of event flow (se Events Specification), including the very last stage, when it reached document. Only after it passed "through" all eventListeners uncanceled, browser should execute its default behavior. So attaching your listener to document was not the reason preventDefault() didn't work, it was because it was the wrong guy for the job :)
Try this:
$('body').click(function(event) {
event.stopPropagation();
event.preventDefault();
event.cancelBubble = true;
event.stopImmediatePropagation();
$(document).css('border-color','');
$(document).css('background-color','');
$(event.target).css('border-color','yellow');
$(event.target).css('background-color','#6BFF70');
return false;
});
Try to bind not only to click event, but as well on mousedown event.
Try this css:
body * {
pointer-events: none;
}
or in jQuery:
$("body *").css("pointer-events", "none");
Try declaring a new window event and then stopping the propagation from there:
var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation)
{
e.stopPropagation();
}
Note that Google uses jsaction="..." instead of onclick="...". Try to use it's unbind method on the specified button.
Also you can use dynamic attachment, like:
$(document).on('click', '*', function
Or throw new Error()(just as a dirty hack)

What causes preventDefault to let the original event through

I don't have an example at hand, but in some situations calling event.preventDefault() lets the original event through (navigating to page, submitting form etc) but returning false helps. What could cause this?
You don't have an example to hand? OK, let me invent one that may or may not be whatever it was you were thinking of.
Remember that return false; is the equivalent of calling both event.preventDefault(); and event.stopPropagation(). EDIT: This applies with jQuery, which explictly implements this behaviour and also normalises event.preventDefault() and event.stopPropagation() for use in all browsers. It doesn't work that way in all browsers with "plain" JS, in fact older IE versions don't support event.preventDefault() at all, they have their own equivalent event.returnValue = false;
If you have nested elements and you handle the same event in several levels then calling event.preventDefault() will not stop the outer elements' event handlers from running, but return false will because it stops propagation of the event.
An example that demonstrates it: http://jsfiddle.net/nnnnnn/KjLv3/
<span>Click me to see an alert</span>
// using jQuery for simplicity in the example:
$("a span").click(function(e){
e.preventDefault();
});
$("a").click(function() {
alert("Hello");
});
The alert will display. If you change the "a span" handler to return false the alert will not display.
event.preventDefault() prevents the browser from performing the default action ( if the event is cancelable ) without stopping further propagation of the event, whereas
return false prevents the event from propagating (or "bubbling up") the DOM, along with preventing the default action.
So,
function() {
return false;
}
// IS EQUAL TO
function(e) {
e.preventDefault();
e.stopPropagation();
}

`return false` in an event handler attached by addEventListener or element.on*

Right let’s get this out the way first. Yes, I want to hide the context menu. No, I’m not trying to prevent someone lifting content off my page. Its intended use is input for an in-browser game and it will be limited to a specific area on the webpage.
Moving from the ideological to the technical...
var mouse_input = function (evt) {
// ...
return false;
}
document.onmousedown = mouse_input; // successful at preventing the menu.
document.addEventListener('mousedown', mouse_input, true); // unsuccessful
Could someone explain to me why the addEventListener version is unable to stop the context menu from firing? The only difference I was able to see in Safari's Web Inspector was that document.onmousedown had a isAttribute value that was true whilst the addEventListener version had the same value as false.
So my unfruitful search suddenly became fruitful.
var mouse_input = function (evt) {
evt.preventDefault();
}
document.addEventListener('contextmenu', mouse_input, false);
Works for Safari, Firefox, Opera. preventDefault() stops the usual actions from happening. I had to change the event that was listened for to accommodate for Safari and it is more logical anyway. Further information: functions that implement EventListener shouldn’t return values so return false had no effect.
To explain the difference .. element.onmousedown = somefunction; is an absolute assignment; you are replacing the event handler on the element. element.addEventListener(...) is, as the name implies, adding a handler in addition to any handler(s) already attached for the event.

event.preventDefault() vs. return false

When I want to prevent other event handlers from executing after a certain event is fired, I can use one of two techniques. I'll use jQuery in the examples, but this applies to plain-JS as well:
1. event.preventDefault()
$('a').click(function (e) {
// custom handling here
e.preventDefault();
});
2. return false
$('a').click(function () {
// custom handling here
return false;
});
Is there any significant difference between those two methods of stopping event propagation?
For me, return false; is simpler, shorter and probably less error prone than executing a method. With the method, you have to remember about correct casing, parenthesis, etc.
Also, I have to define the first parameter in callback to be able to call the method. Perhaps, there are some reasons why I should avoid doing it like this and use preventDefault instead? What's the better way?
return false from within a jQuery event handler is effectively the same as calling both e.preventDefault and e.stopPropagation on the passed jQuery.Event object.
e.preventDefault() will prevent the default event from occuring, e.stopPropagation() will prevent the event from bubbling up and return false will do both. Note that this behaviour differs from normal (non-jQuery) event handlers, in which, notably, return false does not stop the event from bubbling up.
Source: John Resig
Any benefit to using event.preventDefault() over "return false" to cancel out an href click?
From my experience, there is at least one clear advantage when using event.preventDefault() over using return false. Suppose you are capturing the click event on an anchor tag, otherwise which it would be a big problem if the user were to be navigated away from the current page. If your click handler uses return false to prevent browser navigation, it opens the possibility that the interpreter will not reach the return statement and the browser will proceed to execute the anchor tag's default behavior.
$('a').click(function (e) {
// custom handling here
// oops...runtime error...where oh where will the href take me?
return false;
});
The benefit to using event.preventDefault() is that you can add this as the first line in the handler, thereby guaranteeing that the anchor's default behavior will not fire, regardless if the last line of the function is not reached (eg. runtime error).
$('a').click(function (e) {
e.preventDefault();
// custom handling here
// oops...runtime error, but at least the user isn't navigated away.
});
This is not, as you've titled it, a "JavaScript" question; it is a question regarding the design of jQuery.
jQuery and the previously linked citation from John Resig (in karim79's message) seem to be the source misunderstanding of how event handlers in general work.
Fact: An event handler that returns false prevents the default action for that event. It does not stop the event propagation. Event handlers have always worked this way, since the old days of Netscape Navigator.
Event handler content attributes and event handler IDL attributes that returns false prevents the default action for that event handler.
What happens in jQuery is not the same as what happens with event handlers. DOM event listeners and MSIE "attached" events are a different matter altogether.
For further reading, see the[ [W3C DOM 2 Events documentation]][1].
Generally, your first option (preventDefault()) is the one to take, but you have to know what context you're in and what your goals are.
Fuel Your Coding has a great article on return false; vs event.preventDefault() vs event.stopPropagation() vs event.stopImmediatePropagation().
When using jQuery, return false is doing 3 separate things when you call it:
event.preventDefault();
event.stopPropagation();
Stops callback execution and returns immediately when called.
See jQuery Events: Stop (Mis)Using Return False for more information and examples.
You can hang a lot of functions on the onClick event for one element. How can you be sure the false one will be the last one to fire? preventDefault on the other hand will definitely prevent only the default behavior of the element.
I think
event.preventDefault()
is the w3c specified way of canceling events.
You can read this in the W3C spec on Event cancelation.
Also you can't use return false in every situation. When giving a javascript function in the href attribute and if you return false then the user will be redirected to a page with false string written.
I think the best way to do this is to use event.preventDefault() because if some exception is raised in the handler, then the return false statement will be skipped and the behavior will be opposite to what you want.
But if you are sure that the code won't trigger any exceptions, then you can go with any of the method you wish.
If you still want to go with the return false, then you can put your entire handler code in a try catch block like below:
$('a').click(function (e) {
try{
your code here.........
}
catch(e){}
return false;
});
The main difference between return false and event.preventDefault() is that your code below return false will not be executed and in event.preventDefault() case your code will execute after this statement.
When you write return false it do the following things for you behind the scenes.
* Stops callback execution and returns immediately when called.
* event.stopPropagation();
* event.preventDefault();
e.preventDefault();
It simply stops the default action of an element.
Instance Ex.:-
prevents the hyperlink from following the URL, prevents the submit button to submit the form. When you have many event handlers and you just want to prevent default event from occuring, & occuring from many times,
for that we need to use in the top of the function().
Reason:-
The reason to use e.preventDefault(); is that in our code so something goes wrong in the code, then it will allow to execute the link or form to get submitted or allow to execute or allow whatever action you need to do. & link or submit button will get submitted & still allow further propagation of the event.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Preventsss page from redirect
<script type="text/javascript">
function doSomethingElse(){
console.log("This is Test...");
}
$("a").click(function(e){
e.preventDefault();
});
</script>
</body>
</html>
return False;
It simply stops the execution of the function().
"return false;" will end the whole execution of process.
Reason:-
The reason to use return false; is that you don't want to execute the function any more in strictly mode.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
Blah
<script type="text/javascript">
function returnFalse(){
console.log("returns false without location redirection....")
return false;
location.href = "http://www.google.com/";
}
</script>
</body>
</html>
Basically, this way you combine things because jQuery is a framework which mostly focuses on HTML elements, you basically preventing the default, but at the same time, you stop propagation to bubble up.
So we can simply say, return false in jQuery is equal to:
return false is e.preventDefault AND e.stopPropagation
But also don't forget it's all in jQuery or DOM related functions, when you run it on the element, basically, it prevents everything from firing including the default behaviour and propagation of the event.
Basically before starting using return false;, first understand what e.preventDefault(); and e.stopPropagation(); do, then if you think you need both at the same time, then simply use it.
So basically this code below:
$('div').click(function () {
return false;
});
is equal to this code:
$('div').click(function (event) {
event.preventDefault();
event.stopPropagation();
});
From my experience event.stopPropagation() is mostly used in CSS effect or animation works, for instance when you have hover effect for both card and button element, when you hover on the button both card and buttons hover effect will be triggered in this case, you can use event.stopPropagation() stop bubbling actions, and event.preventDefault() is for prevent default behaviour of browser actions. For instance, you have form but you only defined click event for the submit action, if the user submits the form by pressing enter, the browser triggered by keypress event, not your click event here you should use event.preventDefault() to avoid inappropriate behavior. I don't know what the hell is return false; sorry.For more clarification visit this link and play around with line #33 https://www.codecademy.com/courses/introduction-to-javascript/lessons/requests-i/exercises/xhr-get-request-iv
My opinion from my experience saying, that it is always better to use
event.preventDefault()
Practically
to stop or prevent submit event, whenever we required rather than return false
event.preventDefault() works fine.
preventDefault() and return false are different ways to prevent the default event from happening.
For example, when a user clicks on an external link, we should display a confirmation modal that asks the user for redirecting to the external website or not:
hyperlink.addEventListener('click', function (e) {
// Don't redirect the user to the link
e.preventDefault();
});
Or we don't want to submit the form when clicking its submit button. Instead, we want to validate the form first:
submitButton.addEventListener('click', function (e) {
// Don't submit the form when clicking a submit
e.preventDefault();
});
Differences
return false doesn't have any effect on the default behavior if you use the addEventListener method to handle an event. It only works when the event handler is declared as an element's attribute:
hyperlink.addEventListener('click', function (e) {
// Does NOT work
return false;
});
// Work
hyperlink.onclick = function (e) {
return false;
};
According to the HTML 5 specifications, return false will cancel the event except for the mouseover event.
Good practices
It's recommended to use the preventDefault method instead of return false inside an event handler. Because the latter only works with using the onclick attribute which will remove other handlers for the same event.
If you're using jQuery to manage the events, then you're able to use return false within the event handler:
$(element).on('click', function (e) {
return false;
});
Before returning the value of false, the handler would do something else. The problem is that if there's any runtime error occurring in the handler, we will not reach the return false statement at the end.
In that case, the default behavior will be taken:
$(element).on('click', function (e) {
// Do something here, but if there's an error at runtime
// ...
return false;
});
We can avoid this situation by using the preventDefault method before performing any custom handler:
$(element).on('click', function (e) {
e.preventDefault();
// Do something here
// The default behavior is prevented regardless of errors at runtime
// ...
});
Good to know
If you're using jQuery to manage the event, then return false will behave the same as the preventDefault() and stopPropagation() methods:
$(element).on('click', function (e) {
// Prevent the default event from happening and
// prevent the event from bubbling up to the parent element
return false;
});

Categories