views:

51

answers:

2

I have a situation where I have a navigation menu that's a series of <ul> lists, the first <li> of which is a tab. I want to make the entire <li> clickable instead of the <a> tag inside the tab. So for example:

<ul id="home">
    <li id="navtab">
        <a id="home-link" onclick="doHome();">HOME</a>
    </li>
</ul>

And the anchors are being created dynamically, so I need to keep this structure. So I'm trying to suss out how to capture the click event at the <li> level, fire the onlick on the <a> tag WITHOUT then re-firing the click at the <li> level and causing recursion.

I'm using jQuery, but that's not necessary in the answer, or even relevant.

I've already tried adding e.stopPropagation() and preventDefault without positive result.

+4  A: 

Instead of using Javascript, why don't utilize CSS and make the <a> a block-level element so that it fills up the entire space of the list item?

#home li a {
  border:solid 1px #000;
  display:block;
}

This should essentially make the entire <li> clickable. However, if you have specific height or padding values applied to the li with CSS, you should move those rules down to this selector for the a.

Josh Stodola
I've had mixed experiences with making `<a>` tags block-level entities.
b. e. hollenbeck
It *always* works great for me, and it's very common these days. Just about every modern CSS-based web site has block-level anchors.
Josh Stodola
Apparently I hadn't tried this in a while - woot!
b. e. hollenbeck
A: 

You could just copy the function up to the parent. This could be problematic depending if you pass the dom object or reference other dom objects relative to argument in that function. I haven't tested this, but it should work ok.

$('#home-link').each(function(){
    var func = this.onclick;
    this.parentNode.onclick = func;
    this.onclick = function(){ };
});
Jage