views:

240

answers:

2

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

+1  A: 

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.

seth
I think you mean e.target.tagName, not evt.target.tagName
Vinay Sajip
thanks. typo when I typed in the code.
seth
+2  A: 

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.

Tivac
Thank you. Works like a charm. I have learned so much from the experts on this site. I think it is the best programming community have ever participated in.
Amy