Erin Drummond
Erin Drummond

Reputation: 5526

How to attach both an onclick() and href to an <a> element, but only have one work at once

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?

Upvotes: 3

Views: 756

Answers (4)

zbynour
zbynour

Reputation: 19817

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).

Upvotes: 0

Robert
Robert

Reputation: 21388

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'); 
});

Upvotes: 0

Ionuț Staicu
Ionuț Staicu

Reputation: 22204

$('.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)

Upvotes: 7

thomasrutter
thomasrutter

Reputation: 117401

Return false from your onclick handler.

Upvotes: 3

Related Questions