Search code examples
htmlangularjsevent-handling

Button inner span not registering click


I have a simple button with a span inside it with some boostrap icon as its class. Nothing serious.

<button ng-click="ctrl.toggleMenuDropDown()" class="  cornerMenuButton menuButton">
                    <span class="fa fa-reorder"></span>
                    Menu
</button>

The problem is that the span part does not register the click. When I click on the rendered button where the icon is, the click is not registered. And I don't know why, or what might be causing that.

But when I add stop propagation to the button it all works fine. Like so:

<button ng-click="ctrl.toggleMenuDropDown(); $event.stopPropagation()" class="  cornerMenuButton menuButton">
                    <span class="fa fa-reorder"></span>
                    Menu
</button> 

It works fine. Why is that?


Solution

  • It's very hard to know why you are using a span inside a button element but clarifying your question:

    You need to add ng-click on the span element also. If you want only the span ng-click to work you need to add event.stopPropagation() to your toggleMenuDropDown(event) function passing event to this function.

    The definition of event.stopPropagation is:

    The event.stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed. Tip: Use the event.isPropagationStopped() method to check whether this method was called for the event.

    $("#but").click(function(event){
      event.stopPropagation();
     });
    
    
    $("#foo").click(function(){
     alert("parent click event fired !");
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
     
     <button id="foo">button
    <span id="but">
    
    <span></button>