sdasdadas
sdasdadas

Reputation: 25096

JQuery Hide() Behaviour

I'm using Firefox and JQuery:

The following code hides the content briefly, but then the content reappears:

$("#calorielink").click(function() {
                $("#A").hide();
                $("#B").hide();
            });

The following code CORRECTLY hides the content:

$("#calorielink").click(function() {
                $("#A").hide();
                $("#B").hide();
                return false;
            });

Why does the return statement have an effect?

Upvotes: 1

Views: 99

Answers (2)

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

return false does the following things for you in an event handler:

  • Prevent's the default action of the event. Assuming #calorieLink is an a, this means the user is not directed to a new page.
  • Stops propagation of the event. The event will not bubble up the DOM. In other words, if you have event handlers attached to elements "upstream" of this element, they will not be notified of the event.
  • Returns from your callback function immediately.

Usually, you just want the first one (you only need to prevent the default action):

$("#calorielink").click(function(event) {
    event.preventDefault(); // Prevent the default action from occurring.
    $("#A").hide();
    $("#B").hide();
});

I would generally recommend against using return false in event handlers. Think about what you want to happen in your event handler, and even if you do need both of the things that return false accomplishes, it's more expressive to write:

event.preventDefault();
event.stopPropagation();

Here's a good read about what return false is actually doing.

Not including return false or stopping the events default action (event.preventDefault()) will cause your code to run and the default behavior of the event will occur as well. This is probably why you're seeing the code run quickly and then the effects disappear.

Upvotes: 3

Yogu
Yogu

Reputation: 9445

Returning false prevents the browser from loading the url that is set with the href attribute of the <a> element.

I think, the element links to the page itself and therefore reloads the page.

Upvotes: 1

Related Questions