Reputation: 25096
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
Reputation: 126042
return false
does the following things for you in an event handler:
#calorieLink
is an a
, this means the user is not directed to a new page.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
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