I have a DOM structure as follows:
<div class="hotspot">
<div class="hotspot_inner">
<div class="hotspot_info">
<div class="inner_box">
<h2><%= hotspot.info.title %></h2>
<p><%= hotspot.info.description.html_safe %></p>
</div>
</div>
</div>
</div>
I also have some CoffeeScript that attaches a click event listener to anything with the class ‘.hotspot’ that makes everything inside the hotspot visible (‘.hotspot_inner’ and down) on click.
Clicking anything with the ‘.hotspot’ class again makes everything inside invisible once more.
The problem is, clicking anything inside the hotspot also triggers the close event attached to its parent.
I’ve tried stopPropagation(), but to no avail. I’ve heard .live has issues like this, but because hotspots are added dynamically, I need to use it.
Any ideas?
The call to
stopPropagation()won’t work because the event has already propagated; that’s how the “live” mechanism works.What you can do instead is to set a flag somewhere, perhaps on the event object itself. The parent handlers can check for that and know that they’re not supposed to do anything.
Alternatively, you could check the event target, which jQuery normalizes as the “target” property of the event object. If the parent handlers see that they’re not the target, they can skip the event. This can get tricky sometimes depending on the nature of your interaction patterns and the structure of the DOM.
You may be interested to learn that
.live()has been deprecated for a couple of years now. With current versions of the library you should use.on(), which combines the abilities of.bind()and.delegate().