HI there,
this is a little sticky situation and I need some advice.
I have a couple of href's like this, across my project.
<a class="not-allowed" href="javascript:void(0)" onclick="showSettingDiv();">Change</a>
<a class="" href="javascript:void(0)" onclick="DeleteSettingDiv();">Delete</a>
Depending on the type of user logged in, I have to have some links do nothing and trigger something else.
I have this function to make that happen:
$('.not-allowed').each(function (e) {
$(this).click(function (e) {
e.preventDefault();
alert("you dont have permission");
})
});
This does fire up the alert, however, it also executes my onclick function too. is there a way I Can stop all javascript functions and execute just this above one?
I realized I could just use .removeAttr() but I am not sure if thats the best way. I mean I might have buttons to restrict or checkbox and radio button to disable.
e.preventDefault will not take care of all that I guess. Anyway, How do I prevent all javascript functions ?
Thanks.
Yes. It is called Capture mode. It works on DOM-compatible browsers. Check out if your JS framework makes this function available for you.
If the capturing EventListener wishes to prevent further processing of the event from occurring it may call the stopProgagation method of the Event interface.
A quick example:
<html>
<body>
<button class="not-allowed" id="btn1" onclick="alert('onclick executed');">BTN1</button>
<button id="btn2" onclick="alert('onclick executed');">BTN2</button>
<script type="text/javascript">
document.addEventListener("click", function (event) {
if (event.target.className.indexOf("not-allowed") > -1) {
event.stopPropagation(); // prevent normal event handler form running
event.preventDefault(); // prevent browser action (for links)
}
}, true);
</script>
</body>
<html>
.preventDefault() does not have an affect on inline event handlers. You would need to remove the functionality completely. Give this a shot:
$('.not-allowed').each(function(i, elem) {
elem.onclick = null;
$(this).click(function (e) {
e.preventDefault();
alert("you dont have permission");
})
});
Simplified example on jsfiddle: http://jsfiddle.net/cJcCJ/
You could bind the click event on a parent element and then bind another click event on the "inactive" elements which will call e.stopPropagation(); to prevent the event from bubbling up to the parent element.
Another solution would be giving the disabled elements a class and doing if($(this).hasClass('disabled')) return; in the handler.
You will need to have to modify the function(s) in onclick (showSettingDiv, DeleteSettingDiv) to check for the permissions, too.
BTW, make sure that you don't only check permissions in JavaScript, you must also do it server-side, or it's very easy to manipulate.
Related
I have the following set-up on my webpage
<div id="clickable">
Here!
</div>
Is there a way I could use to avoid the click event for the div to be triggered. I presume it has something to do with setting something in the onclick attribute for the anchor tag but trying simple things like e.preventDefault() haven't worked.
Help? Thanks!
e.preventDefault(); wont work in onclick attributes because e is not defined. Also e.preventDefault(); isn't want you want to stop bubbling, you need e.stopPropagation();
Either use;
onclick="$(this).stopPropagation();"
on your anchor, or
$(a).click(function(e){
e.stopPropagation();
});
in your events.
e.preventDefault() does not stop the event from bubbling up. You need to add e.stopPropagation(), or replace it with return false.
You can read more on the differences between these three in this answer.
Vanilla JS expansion on the accepted answer. event.stopPropagation() is the most specific and predictable method for preventing events from bubbling to parent containers without disabling the default behavior. In the following examples, the <a/> will not trigger the alert even though it is contained in a clickable <div/>.
<script>
function linkHandler(event) {
event.stopPropagation()
}
</script>
<div onclick="alert('fail)">
Link
</div>
You can use onclick="return false;"
stuff
You can return false; or make sure your function is using e as an argument
$("#clickable a").click(function(e){
//stuff
e.preventDefault;
});
I have a click event that is defined already. I was wondering what the best way would be to append another event handler to this event without touching this code (if possible).
Is there a way to just append another event handler to the already defined click event?
This is the current click event definition:
$(".HwYesButton", "#HwQuizQuestions")
.append("<a href='javascript:void(0);' rel='.HwYesButton'>Yes</a>")
.click(function(event) {
var button = $(this).parent();
var questionId = button.attr('id');
$iadp.decisionPoint["HwQuizYourself"].Input.inputProvided(questionId);
button.find(".HwNoButton").removeClass("HwButtonSelected");
$(this).addClass("HwButtonSelected");
button.removeClass("HwQuestionSkipped");
$iadp.flat.setBoolean(questionId, true);
return false;
});
The only thing you can do is to attach another (additional) handler:
$(".HwYesButton", "#HwQuizQuestions").click(function() {
// something else
});
jQuery will call the handlers in the order in which they have been attached to the element.
You cannot "extend" the already defined handler.
Btw. your formulation is a bit imprecise. You are not defining a click event. You are only attaching click event handlers. The click event is generated by the browser when the user clicks on some element.
You can have as many click handlers as you want for one element. Maybe you are used to this in plain JavaScript:
element.onclick = function() {}
With this method you can indeed only attach one handler. But JavaScript provides some advanced event handling methods which I assume jQuery makes use of.
I know this is an old post, but perhaps this can still help someone since I still managed to stumble across this question during my search...
I am trying to do same kind of thing except I want my action to trigger BEFORE the existing inline onClick events. This is what I've done so far and it seems to be working ok after my initial tests. It probably won't handle events that aren't inline, such as those bound by other javascipt.
$(function() {
$("[onClick]").each(function(){
var x = $(this).attr("onClick");
$(this).removeAttr("onClick").unbind("click");
$(this).click(function(e){
// do what you want here...
eval(x); // do original action here...
});
});
});
You can just write another click event to the same and the both will get triggered. See it here
<a id="clickme">clickme</a>
<script>
$('#clickme').click(function () {
alert('first click handler triggered');
});
$('#clickme').click(function () {
alert('second click handler triggered');
});
</script>
Ajax can complicate the issue here. If you call two events the first being an ajax call, then the second event will probably fire well before the response comes back.
So even though the events are being fired in the correct order, what you really need is to get in to the callback function in the ajax call.
It's difficult to do without editing the original code.
Yes you can. Let's say that I have a tag cloud, and clicking a tag will remove the tag by default. Something like:
<div class="tags">
<div class="tag">Tag 1</div>
<div class="tag">Tag 2</div>
</div>
<script>
$(document).ready(function(){
$('.tag').click(function(e){
e.preventDefault();
$(this).fadeOut('slow',function(){
$(this).remove();
});
return false;
});
});
</script>
Now let's say that's bundled into an included library for a project, but you want to provide a developer-friendly way to intercept those click events and prompt the user an AYS (Are You Sure?) dialog. In your mind you might be thinking something like:
<script>
$(document).ready(function(){
$('.tag').beforeRemove(function(){
if (AYS() === false) {
return false; // don't allow the removal
}
return true; // allow the removal
});
});
</script>
The solution, therefore, would be:
<div class="tags">
<div class="tag">Tag 1</div>
<div class="tag">Tag 2</div>
</div>
<script><!-- included library script -->
$(document).ready(function(){
$.fn.beforeRemove = $.fn.click;
$('BODY').on('click','.tag',function(e){
e.preventDefault();
console.log('debug: called standard click event');
$(this).fadeOut('slow',function(){
$(this).remove();
});
return false;
});
});
</script>
<script><!-- included in your page, after the library is loaded -->
$(document).ready(function(){
$('.tag').beforeRemove(function(){
var sWhich = $(this).text();
console.log('debug: before remove - ' + sWhich);
return false; // simulate AYS response was no
// change return false to true to simulate AYS response was yes
});
});
</script>
In this example, the trick is that we extended jQuery with a beforeRemove trigger that is a duplicate of the click trigger. Next, by making the library utilize the $('BODY').on('click','.tag',function(e){...}); handler, we made it delay and call after our page's beforeRemove trigger fired. Therefore, we could return false in beforeRemove if we got a negative AYS condition and therefore not allow the click event to continue.
So, run the above and you'll see that clicks on the tags won't remove the item. Now, switch the beforeRemove function to return true (as if you had a positive response to an AYS prompt), and the click event is allowed to continue. You have appended an event handler to a preexisting click event.
It is said that when we handle a "click event", returning false or calling event.preventDefault() makes a difference, in which
the difference is that preventDefault
will only prevent the default event
action to occur, i.e. a page redirect
on a link click, a form submission,
etc. and return false will also stop
the event flow.
Does that mean, if the click event is registered several times for several actions, using
$('#clickme').click(function() { … })
returning false will stop the other handlers from running?
I am on a Mac now and so can only use Firefox and Chrome but not IE, which has a different event model, and tested it on Firefox and Chrome by adding 3 handlers, and all 3 handlers ran without any stopping…. so what is the real difference, or, is there a situation where "stopping the event flow" is not desirable?
This is related to
Using jQuery's animate(), if the clicked on element is "<a href="#" ...> </a>", the function should still return false?
and
What's the difference between e.preventDefault(); and return false?
hopes this code can explain it to you...
html
<div>
click me
click me
</div>
jquery
$('div').click(function(){
alert('I am from <div>');
});
$('a.a1').click(function(){
alert('I am from <a>');
return false; // this will produce one alert
});
$('a.a2').click(function(e){
alert('I am from <a>');
e.preventDefault(); // this will produce two alerts
});
demo
or
$('div').click(function(){
alert('I am from <div>');
});
$('a').click(function(){
alert('I am from <a>');
});
$('a.a1').click(function(){
alert('I am from <a class="a1">');
return false;
});
$('a.a2').click(function(e){
alert('I am from <a class="a2">');
e.preventDefault();
});
demo 2
Writing return false or e.preventDefault() will not prevent other handlers from running.
Rather, they will prevent the browser's default reaction, such as navigating to a link.
In jQuery, you can write e.stopImmediatePropagation() to prevent other handlers from running.
return false and preventDefault() are there to prevent the browser's default action associated with an event (for example, following a link when it's clicked). There is a different technique to achieve this for each of three different scenarios:
1. An event handler added using addEventListener() (non-IE browsers). In this case, use the preventDefault() method of the Event object. Other handlers for the event will still be called.
function handleEvent(evt) {
evt.preventDefault();
}
2. An event handler added using attachEvent() (IE). In this case, set the returnValue property of window.event to true. Other handlers for the event will still be called, and may also change this property.
function handleEvent() {
window.event.returnValue = false;
}
3. An event handler added using an attribute or event handler property.
<input type="button" value="Do stuff!" onclick="return handleEvent(event)">
or
button.onclick = handleEvent;
In this case, return false will do the job. Any other event handlers added via addEventListener() or attachEvent() will still be called.
function handleEvent() {
return false;
}
Sometimes an event listener wants to cancel the sideeffects of the event is is interested in. Imagine a textbox which you wish to only allow numbers. Because textboxes can accept anything it becomes necessary to tell the browser to ignore non numbers that are typed. This is achieved by listening the key events and returning false if the wrong key is typed.
This doesn't completely answer your question, but the other day I used YUI's e.preventDefault() on an <a> element to squash the href action, as I only wanted the JavaScript onclick event to have control (unless no JS detected). In this situation stopping the entire chain of events wouldn't effect me.
But a couple days before that, I had an <input type="checkbox"> nested inside a <label> element, and I had to use a conditional in the event handler to determine if the clicked target was a label, as neither e.preventDefault() nor e.stopEvent() stopped my 'click' event from (legitimately) triggering twice (except in IE6).
What would have been nice is the ability to squash an entire chain of related events, since I'd already tried propagation and return false ;, but I was always going to get a 2nd event fire thanks to my label element.
Edit: I wouldn't mind knowing how jQuery would've handled my double-event situation, if anyone's keen to comment on that.
I have a timer in my JavaScript which needs to emulate clicking a link to go to another page once the time elapses. To do this I'm using jQuery's click() function. I have used $().trigger() and window.location also, and I can make it work as intended with all three.
I've observed some weird behavior with click() and I'm trying to understand what happens and why.
I'm using Firefox for everything I describe in this question, but I am also interested in what other browsers will do with this.
If I have not used $('a').bind('click',fn) or $('a').click(fn) to set an event handler, then calling $('a').click() seems to do nothing at all. It does not call the browser's default handler for this event, as the browser does not load the new page.
However, if I set an event handler first, then it works as expected, even if the event handler does nothing.
$('a').click(function(){return true;}).click();
This loads the new page as if I had clicked the a myself.
So my question is twofold: Is this weird behavior because I'm doing something wrong somewhere? and why does calling click() do nothing with the default behavior if I haven't created a handler of my own?
As Hoffman determined when he tried to duplicate my results, the outcome I described above doesn't actually happen. I'm not sure what caused the events I observed yesterday, but I'm certain today that it was not what I described in the question.
So the answer is that you can't "fake" clicks in the browser and that all jQuery does is call your event handler. You can still use window.location to change page, and that works fine for me.
Another option is of course to just use vanilla JavaScript:
document.getElementById("a_link").click()
Interesting, this is probably a "feature request" (ie bug) for jQuery. The jQuery click event only triggers the click action (called onClick event on the DOM) on the element if you bind a jQuery event to the element. You should go to jQuery mailing lists ( http://forum.jquery.com/ ) and report this. This might be the wanted behavior, but I don't think so.
EDIT:
I did some testing and what you said is wrong, even if you bind a function to an 'a' tag it still doesn't take you to the website specified by the href attribute. Try the following code:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
/* Try to dis-comment this:
$('#a').click(function () {
alert('jQuery.click()');
return true;
});
*/
});
function button_onClick() {
$('#a').click();
}
function a_onClick() {
alert('a_onClick');
}
</script>
</head>
<body>
<input type="button" onclick="button_onClick()">
<br>
<a id='a' href='http://www.google.com' onClick="a_onClick()"> aaa </a>
</body>
</html>
It never goes to google.com unless you directly click on the link (with or without the commented code). Also notice that even if you bind the click event to the link it still doesn't go purple once you click the button. It only goes purple if you click the link directly.
I did some research and it seems that the .click is not suppose to work with 'a' tags because the browser does not suport "fake clicking" with javascript. I mean, you can't "click" an element with javascript. With 'a' tags you can trigger its onClick event but the link won't change colors (to the visited link color, the default is purple in most browsers). So it wouldn't make sense to make the $().click event work with 'a' tags since the act of going to the href attribute is not a part of the onClick event, but hardcoded in the browser.
If you look at the code for the $.click function, I'll bet there is a conditional statement that checks to see if the element has listeners registered for theclick event before it proceeds. Why not just get the href attribute from the link and manually change the page location?
window.location.href = $('a').attr('href');
Here is why it doesn't click through. From the trigger function, jQuery source for version 1.3.2:
// Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
if ( (!elem[type] || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
event.result = false;
// Trigger the native events (except for clicks on links)
if ( !bubbling && elem[type] && !event.isDefaultPrevented() && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
this.triggered = true;
try {
elem[ type ]();
// Prevent Internet Explorer from throwing an error for some hidden elements
}
catch (e)
{
}
}
After it calls handlers (if there are any), jQuery triggers an event on the object. However it only calls native handlers for click events if the element is not a link. I guess this was done purposefully for some reason. This should be true though whether an event handler is defined or not, so I'm not sure why in your case attaching an event handler caused the native onClick handler to be called. You'll have to do what I did and step through the execution to see where it is being called.
JavaScript/jQuery doesn't support the default behavior of links "clicked" programmatically.
Instead, you can create a form and submit it. This way you don't have to use window.location or window.open, which are often blocked as unwanted popups by browsers.
This script has two different methods: one that tries to open three new tabs/windows (it opens only one in Internet Explorer and Chrome, more information is below) and one that fires a custom event on a link click.
Here is how:
HTML
<html>
<head>
<script src="jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="script.js" type="text/javascript"></script>
</head>
<body>
<button id="testbtn">Test</button><br><br>
Google<br>
Wikipedia<br>
Stack Overflow
</body>
</html>
jQuery (file script.js)
$(function()
{
// Try to open all three links by pressing the button
// - Firefox opens all three links
// - Chrome only opens one of them without a popup warning
// - Internet Explorer only opens one of them WITH a popup warning
$("#testbtn").on("click", function()
{
$("a").each(function()
{
var form = $("<form></form>");
form.attr(
{
id : "formform",
action : $(this).attr("href"),
method : "GET",
// Open in new window/tab
target : "_blank"
});
$("body").append(form);
$("#formform").submit();
$("#formform").remove();
});
});
// Or click the link and fire a custom event
// (open your own window without following
// the link itself)
$("a").on("click", function()
{
var form = $("<form></form>");
form.attr(
{
id : "formform",
// The location given in the link itself
action : $(this).attr("href"),
method : "GET",
// Open in new window/tab
target : "_blank"
});
$("body").append(form);
$("#formform").submit();
$("#formform").remove();
// Prevent the link from opening normally
return false;
});
});
For each link element, it:
Creates a form
Gives it attributes
Appends it to the DOM so it can be submitted
Submits it
Removes the form from the DOM, removing all traces *Insert evil laugh*
Now you have a new tab/window loading "https://google.nl" (or any URL you want, just replace it). Unfortunately when you try to open more than one window this way, you get an Popup blocked messagebar when trying to open the second one (the first one is still opened).
More information on how I got to this method is found here:
Opening new window/tab without using window.open or window.location.href
Click handlers on anchor tags are a special case in jQuery.
I think you might be getting confused between the anchor's onclick event (known by the browser) and the click event of the jQuery object which wraps the DOM's notion of the anchor tag.
You can download the jQuery 1.3.2 source here.
The relevant sections of the source are lines 2643-2645 (I have split this out to multiple lines to make it easier to comprehend):
// Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
if (
(!elem[type] || (jQuery.nodeName(elem, 'a') && type == "click")) &&
elem["on"+type] &&
elem["on"+type].apply( elem, data ) === false
)
event.result = false;
You can use jQuery to select the jQuery object for that element. Then, get the underlying DOM element and call its click() method.
By id:
$("#my-link").each(function (index) { $(this).get(0).click() });
Or use jQuery to click a bunch of links by CSS class:
$(".my-link-class").each(function (index) { $(this).get(0).click() });
Trigger a hyperlink <a> element that is inside the element you want to hookup the jQuery .click() to:
<div class="TopicControl">
<div class="articleImage">
<img src="" alt="">
</div>
</div>
In your script you hookup to the main container you want the click event on. Then you use standard jQuery methodology to find the element (type, class, and id) and fire the click. jQuery enters a recursive function to fire the click and you break the recursive function by taking the event 'e' and stopPropagation() function and return false, because you don't want jQuery to do anything else but fire the link.
$('.TopicControl').click(function (event) {
$(this).find('a').click();
event.stopPropagation();
return false;
});
Alternative solution is to wrap the containers in the <a> element and place 's as containers inside instead of <div>'s. Set the spans to display block to conform with W3C standards.
It does nothing because no events have been bound to the event. If I recall correctly, jQuery maintains its own list of event handlers that are bound to NodeLists for performance and other purposes.
If you need this feature for one case or very few cases (your whole application is not requiring this feature). I would rather leave jQuery as is (for many reasons, including being able to update to newer versions, CDN, etc.) and have the following workaround:
// For modern browsers
$(ele).trigger("click");
// Relying on Paul Irish's conditional class names,
// <https://www.paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/>
// (via HTML5 Boilerplate, <https://html5boilerplate.com/>) where
// each Internet Explorer version gets a class of its version
$("html.ie7").length && (function(){
var eleOnClickattr = $(ele).attr("onclick")
eval(eleOnClickattr);
})()
To open hyperlink in the same tab, use:
$(document).on('click', "a.classname", function() {
var form = $("<form></form>");
form.attr(
{
id : "formid",
action : $(this).attr("href"),
method : "GET",
});
$("body").append(form);
$("#formid").submit();
$("#formid").remove();
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;
});