Correct use of return false

Source: Internet
Author: User

"Return false" was misused so badly because it looked like it was done with the work we gave it, the browser would no longer redirect us to the link in the href, and the form would not be submitted, but what was wrong with that?

Perhaps the first example you'll see when you start learning about jquery event handling is how to prevent the browser from performing the default behavior, such as the following code that demonstrates the Click event:

Copy CodeThe code is as follows:
$ ("A.toggle"). Click (function () {
$ ("#mydiv"). Toggle ();
return false; Prevent browser from visiting ' # '
});
This function uses toggle to show or hide #mydiv, and then prevents the browser from continuing to access the links specified in the href.

Examples like the one above will allow the user to develop a bad habit of using "return false" to prevent the browser from performing the default behavior, and in this article I will discuss two very important topics that prevent the browser from performing the default behavior:

• Choose the correct method: return False or Preventdefault,stoppropagation or stopimmediatepropagation
• Choose the right location, start, end, or somewhere in the middle: which part of the event callback should you cancel the browser to perform the default behavior?

Note: When I mention event bubbling in this article, I would like to express that most events are triggered first on the initial DOM, and then up through the DOM tree, on each level of the parent element, Events do not bubble up on sibling nodes or child nodes (we call it event capturing when events are bubbling down), and you can learn more about event blistering and capture here.

Choose the Right method

"Return false" was misused so badly because it looked like it was done with the work we gave it, the browser would not redirect us to the link in the href, the form would not be submitted, but what was wrong with it?

What exactly did "return false" do?

When you call "return false" every time, it actually does 3 things:

Event.preventdefault ();
event.stoppropagation ();
• Stop the callback function to execute and return immediately.
"Wait," you called up! I just want the browser to stop performing the default behavior, and I don't need it to do another 2 things.

There are only preventdefault in these 3 things that prevent the browser from continuing to perform the default behavior, unless you want to stop the event bubbling, otherwise using return false will put a big risk on your code, let's take a real example to see what the consequences of such misuse would be:

Here is the HTML we used to demonstrate:

Copy CodeThe code is as follows:
<div class= "POST" >
<div class= "Content" >
Teaser text ...
</div>
</div>
<div class= "POST" >
<div class= "Content" >
Teaser text ...
</div>
</div>
Now suppose we want to dynamically load the article into DIV.CONTENTD when the user clicks on the article title:
Copy CodeThe code is as follows:
JQuery (document). Ready (function ($) {
$ ("Div.post h2 a"). Click (function () {
var a = $ (this),
href = a.attr (' href '),//Let jQuery normalize ' href ',
Content = A.parent (). Next ();
Content.load (href + "#content");
return false; "Cancel" The default behavior of following the link
});
});
This code works (at least for now), but if we continue with this idea, if I want to add an active class to the user when he clicks on a div.post element (or any one of its children), I need to add a div.post to the Click Callback:
Copy CodeThe code is as follows:
Inside Document Ready:
var posts = $ ("Div.post");
Posts.click (function () {
Remove active from all Div.post
Posts.removeclass ("active");
Add it back to this one
$ (this). AddClass ("active");
});
Now, if we click on the title of a post, will this code work? The answer is no, because we used the return false in the header's click Callback instead of the one we should use, "return false" equals Event.preventdefault (); plus event.stoppropagation (); , the event bubbling is terminated, and the Click event is not bubbled up to Div.post, and the event callbacks we add to it will of course not be called.

The situation is even worse if we mix it up with live or delegate events.

Copy CodeThe code is as follows:
$ ("a"). Click (function () {
Do something
return false;
});

$ ("a"). Live ("Click", Function () {
This WON ' T fire
});
So what do we really need?

Preventdefault ()

In most cases, when you use return false, what you actually need is e.preventdefault (). To use E.preventdefault, you need to make sure that you pass the event parameter to your fallback function (in this case, the E):

Copy CodeThe code is as follows:
$ ("a"). Click (function (e) {
E = = our event data
E.preventdefault ();
});
It will do all the work for us, but it will not prevent the parent node from continuing to handle the event, but keep in mind that the less restrictions you put in your code, the more flexible your code is and the easier it is to maintain.

Stoppropagation ()

But there are cases where you might need to stop the event bubbling, let's take a look at the following example:

Copy CodeThe code is as follows:
<div class= "POST" >
Normal text and then a <a href= "http://jb51.net" >link</a> "+" and then more text.
</div>
Now, let's assume that if you order a div with the exception of a link, we want something to happen (like changing the background), but it doesn't affect the behavior of the user clicking a link (from the usability point of view, this is not a good example, you might not want the user to click anywhere else).
Copy CodeThe code is as follows:
$ ("Div.post"). Click (function () {
Do the first thing;
});

$ ("Div.post a"). Click (function (e) {
Don ' t cancel the browser ' s default action
and don ' t bubble this event!
E.stoppropagation ();
});
In this case, if we use the return False,div Click event will not be triggered, but the user will not reach the link they point to.

Stopimmediatepropagation ()

This method stops an event from continuing, even if other handler functions are bound on the current object, and all events bound to an object are executed in the binding order, and take a look at the following example:

Copy CodeThe code is as follows:
$ ("div a"). Click (function () {
Do something
});

$ ("div a"). Click (function (e) {
Do something else
E.stopimmediatepropagation ();
});

$ ("div a"). Click (function () {
This never FIRES
});

$ ("div"). Click (function () {
This never FIRES
});
You might think this example looks awkward, yes, but sometimes it does, and if your code is very complex, then different widgets and plugin can add events on the same object, and if that's the case, Then you need to understand and use stopimmediatepropagation.

return False

You can use "return false" only if you need Preventdefault and stoppropagation at the same time, and your code can accept that the default behavior of the browser is stopped until your callback execution finishes. However, I strongly recommend that you do not use this method in your demo code for other jquery developers, as this will cause more misuse, and use "return false" only if you are sure that you are not in a position to do so.

Select the appropriate location

If you use "return false", it will only cancel the browser's default behavior at the end of the execution of your callback function, but with e.preventdefault, we have more options to stop the browser from executing the default action at any time, regardless of which part of the function you put it in.

1. During the development phase, you should always put it on the first line. The last thing you want to do is you're debugging. When you change a form to an Ajax commit, it's already been submitted in the old way.

2. Product stage, if you have a progressive enhancement (progressive enhancement), put it at the end of the callback, or the logical end point, if you are using progressive enhancement on a normal page, Then you need to consider the handling of linked click events and form submission events on the server side if the browser does not support JS (or is disabled). The advantage here is that we do not consider the case of turning off JS, only consider support JS when the strong crazy, if your callback code error throws an exception, let us look at the following code:

Copy CodeThe code is as follows:
var data = {};
$ ("a"). Click (function (e) {
E.preventdefault (); Cancel default behavior
Throws an error because ' my ' is undefined
$ ("Body"). Append (Data.my.link);
The original link doesn ' t work and the ' cool '
JavaScript has broken. The user is left with nothing!
});
Now, let's take a look at the same event, put the Preventdefault call on the bottom of the effect:
Copy CodeThe code is as follows:
>
var data = {};
$ ("a"). Click (function (e) {
Throws an error because ' my ' is undefined
$ ("Body"). Append (Data.my.link);

This is never reached, and your website
Falls back to using the ' href ' instead of this
"Cool" broken javascript!
E.preventdefault (); Cancel default behavior
});
This is also valid for form submissions, you can better deal with the situation of error, do not expect your code to work properly, in the event of an error, the correct response is always better than the assumption that the code will not be wrong.

3. In the product stage, if the function of this design JS, it should also be placed in the first line.

Remember, it doesn't have to be the first line of the function, but the sooner the better, the principle here is that if the function is implemented via JS (not involving server-side interaction), then there is no need to consider compatibility, in which case adding the first line prevents the # character from appearing in the URL, but obviously, You should also add as many error-handling code as possible to prevent users from being overwhelmed by errors.

Conclusion

I hope this article conveys enough information to make the right choice when you need to prevent the browser from performing the default behavior. Remember, only use "return false" when you really understand what you are doing, and make sure that you invoke the appropriate code in the correct place of the function. Finally, keep your code as flexible as possible, and try not to "return FALSE"!

Correct use of return false

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.