views:

72

answers:

4

Hi,

I have an element like so:

<a class='link' href='/page1'>Page 1</a>

It has a click handler attached like so:

$('.link').click(function() { loadPage('page1'); });

When the link is clicked, the new page loads. However, there are two ways of loading the new page. One is via AJAX, which figures out which elements have changed between the pages and reloads sections without refreshing based on that, and one which loads via a normal GET request.

I would like to set the href of the link to the URL for normal loading, and the onlick() to call the javascript function that does the AJAX loading. However, they are both firing when I click the link, resulting in the page refreshing completely.

Is there a way to prevent the "href" from taking effect when Javascript is available?

+3  A: 

Return false from your onclick handler.

thomasrutter
duh, that was so simple. Thanks!
Erin Drummond
I like simple answers! Alternatively, you could use event.preventDefault() as others have said, but returning false (in jQuery) will always work for what you want to do. If you want a detailed explanation of the difference, see here: http://css-tricks.com/return-false-and-prevent-default/
thomasrutter
+7  A: 
$('.link').click(function() { loadPage('page1'); return false });

Or

$('.link').click(function(e) { e.preventDefault(); loadPage('page1'); });

First is also stop bubbling. Second, only prevent... default action (*which is going to a link)

Ionut Staicu
@lonut actually you should use both. return false may not fire if loadPage() throws an error
Ben Rowe
If loadPage() throws an error, you probably (this is an assumtion) don't want it the return false to fire.
thomasrutter
uhm... I think if you have an error with `loadPage()` the link will act normally, either you use `return false` or `preventDefault()` (not so sure though, i write bulletproof code. lol :D )
Ionut Staicu
A: 

You can do this

<a class='link' href='/page1'>Page 1</a>

$('.link').click(function(e) { 
e.preventDefault(); // Prevents the default action, i.e. following the href
loadPage('page1'); 
});
Robert
A: 

A short description of the issue (difference between return false; and e.preventDefault();) is here. Also e.stopPropagation(); could be needed to consider, especially due to the case when loadPage() throws an error (as noted by Ben Rowe).

zbynour