When should I use return false in jquery function? When should I use return false in jquery function? jquery jquery

When should I use return false in jquery function?


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 elementthat references the DOM element. Read more on the topic at jQuery's this: demystified.


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.


In the scope of the click handler, this is the unwrapped DOM element. $(this) wraps it and returns a jQuery element. It is common practice to wrap this once and make it available within the scope as that, or often $this (prefixing variable names with $ is a convention to indicate a jQuery element).

Your example could therefore be written as

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