Maria Söderberg
Maria Söderberg

Reputation: 150

How do I prevent a href to be followed in IE when clicking on a links child elements but still execute the method bound to the a tag?

Edit: The same problem seems to occur with events bound with bind('click').

How do I to prevent a live()-bound link from being followed, whether I click on the link itself or any of its child elements?

With the following markup:

<a class='dynamiclink' href='file.htm'>Some text <span> more text </span></a>

And some javascript (with jQuery):

$('a.dynamiclink').live('click', function (e) {
  e.preventDefault();   // only valid for when the target was the link
  // do stuff
  return false;     // dont follow the link. Also prevent further bubbling for live()
});

If we click the link our e.target will contain the link and e.preventDefault() will prevent the link from being followed. However, if we click on the span tag, e.target will contain it instead and e.preventDefault() does nothing useful.

return false seem to prevent all browsers except ie6 and ie7 (ie8 not tested) from following the link, but I need ie6/7 to work.

It if helps, the event supplied to live() seems to be specially made by jQuery for the live()-method. It lacks most of the attributes of a regular event object, like originalTarget. On jQuery and live()-events http://api.jquery.com/live/

Upvotes: 2

Views: 2347

Answers (2)

giorgian
giorgian

Reputation: 3825

The most probable cause is an error occurring before the return false; statement, on an invalid markup. Double-check for errors.

Upvotes: 0

karim79
karim79

Reputation: 342635

Try:

$('a.dynamiclink').live('click', function() {
   return false;
}).children().click(function() { // or .find('span').click(function() {
   return false;
});

or:

$('a.dynamiclink, a.dynamiclink li').live('click', function() {
   return false;
}).

Upvotes: 2

Related Questions