Make onclick handler ignore link clicks

I have my own onclick handler for a block element (configured with jQuery.click () method). This block element can contain links.

I'm sure this is possible, so how can I return the handler if it was a link that I clicked on (so that the link is visited without running my code)?

+2


source to share


4 answers


Check the event object to see if the target is an anchor tag and will return true:



$("div").click(function(eventObject){

    if($(eventObject.target).is("a"))
        return true;

    //run your code
});

      

+6


source


inside your click event, you can check what the tag is:



$("#myDiv").click(function(e) {
  if (e.target.tagName.toLowerCase() == "a") {
    return true; //link clicked
  } else {
    //run your usual div click code here...
  }
});

      

+2


source


how about testing if an element is an anchor or not inside a click function?

if(this.tagName() == "a")return true;

      

I have not tested it, check and answer

0


source


Validation nodeName

event.target

does not work if your links have children (for example, <span>

or <img>

).

Instead, try picking up the tree from event.target

(deepest element) to event.currentTarget

(event the event handler was registered for) and check if any of these elements are available:

$("div").click(function(event) {
    if (clickableBetweenTargetAndCurrentTarget(event))
        return; // This click was probably already handled.
    doSomething();
});

function clickableBetweenTargetAndCurrentTarget(event) {
    for (var el = event.target; el && el != event.currentTarget; el = el.parentNode) {
        if (isClickable(el))
            return true;
    }
    return false;
}

function isClickable(el) {
    // TODO: Customize this as appropriate for your webpage.
    return el.nodeName == 'A' || el.nodeName == 'BUTTON';
}

      

Demo: http://jsbin.com/fojaco/2/

Note that you will need to configure isClickable for your specific webpage; it's hard / impossible to indicate if an element is generally available.

An alternative approach would be to make sure all clickable descendants are called event.preventDefault()

, then your div click listener should only check event.defaultPrevented

(IE9 +). Or descendants could be named event.stopPropagation()

as suggested in another answer , but calling stopPropagation could lead to subtle bugs .

0


source







All Articles