views:

237

answers:

2

I'm capturing a click on any given LI in:

<ul>
    <li class="opt">Text 1</li>
    <li class="opt">Text 2</li>
</ul>

With the code:

$('.opt').live('click', function(event) {
    console.log("Click!");
}

and it works wonderfully :) However, I also need to support the ability for nested block elements to exist inside the LI, without changing my javascript code. The above javascript does not fire when Text 1 in clicked in this case:

<ul>
    <li class="opt">
        <div>
            <div>
                <span>Text 1</span>
            </div>
        </div>
    </li>
</ul>

I've read that jQuery events "bubble up" through the DOM, but unfortunately no such bubbling is occurring here. What's the cleanest way to capture a click event inside an LI when I'm not sure of what other elements might be inside of it?

A: 

You need a dot on that class selector, then it should work:

$('.opt').live('click', function(event) {
    console.log("Click!");
}

Unless you're doing something abnormal (e.g. .stopPropogation() on a clicked child), the event should bubble right up all by itself.

Nick Craver
My fault -- I have the dot there in my code, but lost it in translation. Even with that, my event doesn't seem to be firing a few layers up.
Tom Frost
@Tom - It fires fine here in all tests...there's something else going on, do you have a test page I can look at?
Nick Craver
Oh my is this ever a facepalm moment. The event was bubbling up fine -- it was my misinterpretation of where event.target points that caused my code to halt. Not a total waste of time though, since I wouldn't have found that error if not for your comments. Thanks, Nick!
Tom Frost
@Tom - That happens to me at least 3 times a week :) Glad you got it working!
Nick Craver
A: 
$('.opt, .opt *').live('click', function(event) {
    console.log("Click!");
}
Mark Brackett
This isn't a great idea, you're going to fire that event a *lot* of times, 1 for each nested element.
Nick Craver