user1841121
user1841121

Reputation: 66

jQuery ignoring child elements events

I have the following list:

  <ul id="menu">
            <li style="background-image:url('Images/X-AFH-Company-Office-Background.png')" id="office">
                <!-- <div style="width:250px;height:300px;position:absolute;" ></div>-->
                <div >Company / Office</div>
                <img src="Images/Employee.png"  onmouseover="this.src='Images/Employee-Stroke.png'" onmouseout="this.src='Images/Employee.png'" />
                <img class="stroke" style="display:none"  src="Images/Employee-Stroke.png" />
            </li>
            <li  style="background-image:url('Images/X-AFH-Hospital-Clinic-Background.png')" id="clinic" >
                <div >Hospital / Clinic</div>
                <img src="Images/Doctor.png"  onmouseover="this.src='Images/Doctor-Stroke.png'" onmouseout="this.src='Images/Doctor.png'" />
               <div style="width:100px;height:350px;position:absolute;left:0;top:0;z-index:21"></div>
                                </li>
            <li style="background-image:url('Images/X-AFH-University-School-Background.png')" id="school">
                 <div >University / School</div>
                <img src="Images/Student.png"  onmouseover="this.src='Images/Student-Stroke.png'" onmouseout="this.src='Images/Student.png'" />

            </li>
etc...

And have a click event on the main <li> on that list. However, the <img /> tags are overflowing from their parent <li>s and are triggering the click event.

How can I only restrict the click event for the list item rather than their children? Even if they are going beyond the width and height of the main li.

Upvotes: 2

Views: 176

Answers (3)

dsgriffin
dsgriffin

Reputation: 68616

You could use stopPropagation() on the child elements to stop it triggering.

Here's an example restricting all images which are children of list elements from triggering an alert:

$("li").click(function(e) {
   alert("Clicking on the li will trigger this, not the img children");
});

$("li img").click(function(e) {
   e.stopPropagation(); // The img children inside li will not trigger the li event.
});

jsFiddle example.

Upvotes: 2

Praveen
Praveen

Reputation: 56509

This is due to Event Capturing and bubbling in javascript. You can find more details in the link provided.

You can prevent this using event.stopPropagation.

Upvotes: 1

billyonecan
billyonecan

Reputation: 20260

As an alternative to the existing answer, you can simply compare the event.target against this (the element the click handler is bound to):

$('li').on('click', function(e) {
   if (e.target === this) {
     // code is only executed when li is clicked
   }
});

Here's a simple demo fiddle

Upvotes: 1

Related Questions