1

I'm not sure how should I resolve the following event bubbling situation in jQuery.

I have a link inside a list element (li), which has an on click event. I would like to put an action on li element, which would call link event (click) and call action on li if user clicks a link inside the list element (I always want to trigger click event on li when li or anything inside is clicked).

How should I accomplish this?

Here's the HTML code:

<li>
   <img src="images/img.png" />
   <a href="/remote/path" data-remote="true">Link</a>
</li>

and jQuery code (which obviosly won't work):

$("li a").click(function(e) {
  e.preventBubble = true;
});

$("li").click(function() {
  $el = $(this).find('a');
  $el.click();
  $(this).addClass('active');
});

What is the most elegant solution to this?

Thanks for help!

all jazz
  • 2,007
  • 2
  • 21
  • 37

2 Answers2

4

If I understood you right, you should use jQuery .stopPropagation() instead of implementing this by yourself.

event.stopPropagation()

Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

And the implementation:

$("li a").click(function(e) {
  e.stopPropagation();
});
Itay
  • 16,601
  • 2
  • 51
  • 72
  • The problem is, that I still get "too much recursion" error, which I thought its because of event bubbling when I click the element. Do you have any idea why is that happening? – all jazz Aug 31 '13 at 10:37
  • I think the issue is that it will loop calling the functions.. please see the link – all jazz Aug 31 '13 at 10:55
  • @Aljaz It's still not clear enough to me what you're trying to do. You want the page to move to the href or not? – Itay Aug 31 '13 at 11:01
  • Also your code isn't using what I've written in the answer at all... Check this fiddle http://jsfiddle.net/itay1989/UWn4e/1/ – Itay Aug 31 '13 at 11:03
1

Try using event.stopPropagation() or event.stopImmediatePropagation()

$("li a").click(function(e) {
  e.stopPropagation();
});

Usually I used to do this using return false; or event.preventDefault()

Better go with return false;, check out the reason here

e.preventDefault() will prevent the default event from occuring, e.stopPropagation() will prevent the event from bubbling up and return false will do both.


From you fidde, it is not necessary to have 2 functions for li and a.

You already have like this

<ul id="some_list">
    <li> <a href="/remote-path" data-remote="true">Some link</a>
    </li>
</ul>

Here it seems li == a, so why you want to 2 different function.

Try like this and check this JSFiddle to know the reason.

<ul id="some_list">
    <li>
        <a href="/remote-path" data-remote="true">Some link</a>Text apart from a
    </li>
</ul>
Community
  • 1
  • 1
Praveen
  • 55,303
  • 33
  • 133
  • 164