Reputation: 50316
I am trying to do a simple hide & show of a DOM on click event.I am showing the loadMenu container on clicking of span#dwnTrigger. But my problem is even when I am clicking on the div#loadMenu , this div#loadMenu is getting hidden. I am not sure how can this happen as the event is attached to span#dwnTrigger.
<span id="dwnTrigger" class="dwnPrint" aria-label="Download" ng-controller="dwnCtrl" > Start
<div class="dwnCtrl menuContainer ng-hide" id="loadMenu">
//rest of DOM
</div>
</span>
Controller
abc.controller('dwnCtrl',['$scope',function($scope){
$scope.$element = $("#dwnTrigger");
($scope.$element).on('click',function() {
if ($("#loadMenu").hasClass('ng-hide')) {
$("#loadMenu").removeClass('ng-hide').addClass('ng-show');
//rest of code
}
else if ($("#loadMenu").hasClass('ng-show')) {
$("#loadMenu").removeClass('ng-show').addClass('ng-hide')
}
})
}]);
Upvotes: 0
Views: 59
Reputation: 1065
This is called event propagation/bubbling
. When you click on an element the event propagates through all it's parents. So as the div#loadMenu
is a child of span#dwnTrigger
the click on div#loadMenu
propagates to span#dwnTrigger
and triggers it's event handler.
You can use 'event.stopPropagation()' to prevent this. You have to bind an click event handler to div#loadMenu
, capture the event and stop propagation.
$('div#loadMenu').click(function(event) {
event.stopPropagation();
});
For more on event.stopPropagation()
https://api.jquery.com/event.stoppropagation/ and https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation
Alternatively you can check which element dispatched the event by event.target
and act based on that. For example your click handler can be like following
($scope.$element).on('click',function(event) {
if($(event.target).closest('#loadMenu').length > 0) {
return;
}
if ($("#loadMenu").hasClass('ng-hide')) {
$("#loadMenu").removeClass('ng-hide').addClass('ng-show');
//rest of code
}
else if ($("#loadMenu").hasClass('ng-show')) {
$("#loadMenu").removeClass('ng-show').addClass('ng-hide')
}
})
For more on event.target
https://developer.mozilla.org/en-US/docs/Web/API/Event/target
Upvotes: 1