Amy Anuszewski
Amy Anuszewski

Reputation: 1853

YUI Event and Links

Using YUI, I have a div, with an attached listener that says if I click on the div, execute a callback function. Inside the div is a series of normal html links to other pages. What I WANT to happen is that if I click a link, I go to that page. But, if I click anywhere in the div outside a link, it executes the callback function.

What is ACTUALLY happening is that if I click a link within the div, it executes the callback function for the div and then immediately navigates away to the linked page.

I know how to keep my click in the div from bubbling up to the document. But, how do I take a regular old html link and stop the click on that from firing off the click event for the div? Do I have to reformat the links as javascript links with their own callbacks and then stop propagation? Or, is there an easier way?

Amy

Upvotes: 1

Views: 766

Answers (2)

seth
seth

Reputation: 37297

You could inspect the tagName on the event.target like so:

YAHOO.util.Event.addListener("container", "click", function(e) { 
  if (e.target.tagName == 'DIV') {
     // do something magical!
  }
}); 

If you end up putting a div inside of an anchor tag though, you'd break this obviously.

Upvotes: 1

Tivac
Tivac

Reputation: 2573

Seth's got the right idea, though it's a good idea to be a bit more specific in your checks.

YAHOO.util.Event.on("container", "click", function(e) {
    var tgt = YAHOO.util.Event.getTarget(e);

    if(tgt.nodeName.toLowerCase() !== 'a') {
        YAHOO.util.Event.preventDefault(e);

        console.log("Not an anchor!"); //TODO: REMOVE DEBUG OUTPUT
    }
});

I built an example page at http://tivac.com/yui2/amy_events.htm just in case you want to see it in action.

Upvotes: 3

Related Questions