When should I use return false in jquery function?

zhuanzhou picture zhuanzhou · May 8, 2011 · Viewed 52.2k times · Source

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?

Answer

gruntled picture gruntled · May 8, 2011

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.