Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use return false in jquery function?

I found lots of functions like this one:

$(function() {     $("body a").click(function() {         alert(this.innerHTML);         return false;     }); }); 

What's the difference between this and $(this) in jquery?

They all have a line return false; - I don't know when I should use return false in jquery function and don't know what's the use of it?

like image 561
zhuanzhou Avatar asked May 08 '11 13:05

zhuanzhou


People also ask

What is the reason for using a return false statement in the following code?

Return statements, in programming languages, are used to skip the currently executing function and return to the caller function. Return statements may/may not return any value. Below is the example of a return statement in JavaScript.

What is the difference between return true and return false in JavaScript?

Using return causes your code to short-circuit and stop executing immediately. The first return statement immediately stops execution of our function and causes our function to return true . The code on line three: return false; is never executed.

What does onclick return false do?

When we write return false; then on click of “Click here !” does not redirect to anywhere.


2 Answers

According to jQuery Events: Stop (Mis)Using Return False (archived link), returning false performs three tasks when called:

  1. event.preventDefault();
  2. event.stopPropagation();
  3. Stops callback execution and returns immediately when called.

The only action needed to cancel the default behaviour is preventDefault(). Issuing return false; can create brittle code. Usually you'd want just this:

$("a").on( 'click', function (e) {     // e == our event data     e.preventDefault(); }); 

And secondly "this" is a DOM element in javascript and "$(this)" is a jQuery element that references the DOM element. Read more on the topic at jQuery's this: demystified.

like image 57
gruntled Avatar answered Oct 05 '22 21:10

gruntled


You're clicking on an anchor, whose default behavior is to navigate somewhere. Returning false may be an attempt to prevent the navigation and keep user on current page/view.

like image 29
Kon Avatar answered Oct 05 '22 20:10

Kon