
Question:
I find it hard to explain, so please request more info if you need it.
I have a div like so:
<div id="clickable">
Some content
<a href="google.com" class="link">Google</a>
<a href="yahoo.com">Yahoo</a>
</div>
I want the div to be clickable, and link to the href of an attribute with class 'link'. This part I have done:
$('#clickable').on 'click', (ev) ->
window.location = $(this).find('.link').attr('href')
return false
But, what should happen is if a user clicks a link within the div, that links location takes precedence. So, in the above example, if you click yahoo it will direct to yahoo. At the moment, it forces google.
Answer1:The call to update window.location
and subsequent return false
(stopping the click's propagation) is happening regardless of the normal behaviour of a link.
Try this:
$('#clickable').on('click', (ev) ->
unless $(ev.target).is('a')
window.location = $('.link', @).attr('href')
false
)
Answer2:This is because of event bubbling. Click on a
bubbles to div
and a click
handler fires on div
which redirects you to .link
. Since the JavaScript is single-threaded, then the top handler is fired as the last one and you are always redirected to .link
.
Try adding this code:
$('#clickable').on 'click', 'a', (ev) ->
ev.stopPropagation()
Don't forget about 'a'
part, which filters click to a
elements. You can use jQuery's filters there.
<strong>EDIT</strong>
Since for unknown reasons the snippet I posted is not working for you, then how about this? (this time replace the code)
$('#clickable').on 'click', (ev) ->
if ev.target.href
window.location = ev.target.href
return
window.location = $(this).find('.link').attr('href')
return false