Amit
Amit

Reputation: 4000

jquery live return false on A tags

I have a click bound as live to an element. The handler returns false after execution, but if the element happens to be an A tag, then the link is also not followed, which is unacceptable...

$('*').live('click', function(){
  // lots of code here
  return false;
});

Now if the element that is clicked on has a path like A>img and the image is clicked on, the A will never be followed. I dont want the click event to propagate any further.

how do I achieve this?

Edit:

It is essential for my application to bind the event to *. Also, the clicks can be made on any element, not just A's. Thus none of the mentioned solutions are suitable for what I wish to achieve.

Upvotes: 0

Views: 549

Answers (3)

Salman Arshad
Salman Arshad

Reputation: 272246

I would not bind a click function to *. You could bind it to the body element; the click will propagate from the element that was clicked to the body element. You can check the element that was originally clicked like this:

$("body").live("click", function (e) {
    if ($(e.originalEvent.target).is("a")) {
        return false;
    }
});

Having said that, you can still do this:

$("*").live("click", function () {
    if ($(this).is("a") == false) {
        return false;
    }
});

Upvotes: 0

rossipedia
rossipedia

Reputation: 59397

What you're looking for is preventDefault()

$('*').live('click', function(e){
  // lots of code here
  e.preventDefault();
  return false; // Don't think this is necessary
});

I'd also like to say that attaching an event to all elements is probably Not A Good Idea.

You'd be better served by attaching to the A tags specifically:

$('a').click(function(e){
    // lots of code here
    e.preventDefault();
    return false;
});

Upvotes: 2

Paul Zaczkowski
Paul Zaczkowski

Reputation: 2888

Try:

if($(this).tagName == 'A')
    return true; // perhaps even { do nothing }
else
    return false;

This might not be the exact code to get the tagname, see this How to extend jQuery to make it easier to retrieve the tagName.

Also see this: http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/

Upvotes: 0

Related Questions