user1787489
user1787489

Reputation: 1007

How can one trigger the onclick of an element without triggering the parent element onclick?

I have a multilayer drop down navigation bar, which, upon hover opens a menu of subcategories. Upon hovering over these subcategories a further list of subcategories is shown.

Any of the categories, subcategories, and sub-subcategories are supposed to be clickable links, which, when clicked, will show search results for the desired level of detail. i.e. food >>> mexican >>>tacos, One can click on any of the three, to get the desired level of depth in their search.

The problem is, when i click on the subcategories, since they are nested in the parent div, i am also clicking on the parent element.

So if i have:

<ul>
<li onclick="queryfunction()">Category</li>
    <ul>
    <li onclick="queryfunction()">Sub-Category</li>
        <ul>
        <li onclick="queryfunction()">Sub-subCategory</li>
        </ul>
   </ul>
</ul>

Clicking on the bottom category triggers all 3 onclick events.

How can i only trigger the one event i want?

Upvotes: 1

Views: 341

Answers (2)

Rohan Kumar
Rohan Kumar

Reputation: 40639

You can pass a type variable for category,sub-category or sub-subcategory with a this variable or can give a class to each level of category, it will help you in that functions also. like

<ul>
<li class="category" onclick="queryfunction(this)">Category</li>
    <ul>
    <li class="sub-category" onclick="queryfunction(this)">Sub-Category</li>
        <ul>
        <li class="sub-subcategory" onclick="queryfunction(this)">Sub-subCategory</li>
        </ul>
   </ul>
</ul>

For using event.stopPropagation() pass a event in that function will solve your problem.

Upvotes: 0

Pankrates
Pankrates

Reputation: 3094

This is commonly referred to as 'event bubbling'
You can use event.stopPropagation()
You can read up on the subject Here
Or the near-duplicate How to stop event bubbling on checkbox click

Upvotes: 2

Related Questions