tags:

views:

36

answers:

2

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/

+2  A: 

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;
}).
karim79
Thanks for answering so fast! However, I don't want to stop the children from triggering my $('a.dynamiclink') function, I need to execute that script. I just need to prevent the browser from following the href set on the link (which I need to be there) afterwards.
Maria Söderberg
And ofcourse, I can do this by using the method above and calling the code I want executed in a separate function. So, I did what karim79 suggested and lifted out the code that was to be run in (a.dynamiclink).live() a separate function which I called from both the (a.dynamiclink) and its children's event handlers.
Maria Söderberg
A: 

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

giorgian
Thankyou, I'll be sure to do that.
Maria Söderberg