Button onclick inside whole clickable div

As @Sergey mentioned, both actions are being triggered due to the Bubbling propagation of events. The event.stopPropagation() will fix it.

Since there is just HTML/JS example, I will also add a React example to fix this onClick inside whole clickable div:

<div onClick={requestSort()}>
  <DefaultButton onClick={(event) => handleRequestClick(event)} />
</div>

And your handle should be something like:

const handleRequestClick = (e) => {
  // this will stop the bubbling effect of the parent and child click events
  e.stopPropagation()

 // your actual handle action
 myLogiccForMyButton()

} 

Note that the recommendation is to not stop the Bubbling if not necessary:

Sometimes event.stopPropagation() creates hidden pitfalls that later may become problems, for instance if you were to be adding an document.addEventListener('click') to catch all clicks, it won't work where clicks are stopped by event.stopPropagation()

Full explanation:

We create a nested menu. Each submenu handles clicks on its elements and calls stopPropagation so that the outer menu won’t trigger. Later we decide to catch clicks on the whole window, to track users’ behavior (where people click). Some analytic systems do that. Usually the code uses document.addEventListener('click'…) to catch all clicks. Our analytic won’t work over the area where clicks are stopped by stopPropagation. Sadly, we’ve got a “dead zone”.


For your two buttons, create a new function, and add this code at the beginning :

event.cancelBubble = true;
if(event.stopPropagation) event.stopPropagation();

Then add your own code.

The Html :

<div onclick="location.href='@Url.Action("SubClass", "Product", new { id = productClass.HierarchyId })';" class="menu-class">
        <img src="~/Images/ClassImages/@imageName" alt="@productClass.HierarchyShort" />
        <div class="menu-class-text">
            <span>@productClass.HierarchyShort</span>
        </div>
        <div class="menu-class-admin-options">
            <button onclick="editClass()">Edit</button><br/>
            <button onclick="deleteClass()"; ">Delete</button>
        </div>
    </div>

The Javascript :

function editClass() {
   event.cancelBubble = true;
   if(event.stopPropagation) event.stopPropagation();

   location.href = '@Url.Action("EditClass", "Product")';
}

function deleteClass() {
   event.cancelBubble = true;
   if(event.stopPropagation) event.stopPropagation();$

   location.href = '@Url.Action("DeleteClass", "Product")'; 
}

Actually both actions(button's and div's) are triggered. You should stop propagation of events using stopPropagation/cancelBubble. Further reading about bubbling: http://javascript.info/tutorial/bubbling-and-capturing


Thanks for all. As say robooneus. I just put this:

<button onclick=" location.href = '@Url.Action("NewClass", "Product")'; event.stopPropagation(); ">Edit</button><br/>

And now is working. Thanks all.