probably event bubbled on wrong element in custom directive

All we need is an easy explanation of the problem, so here it is.

My goal is to flip a simple element on page on mouse click. It works but not on every click. I must click several times in different places across the tile and then the tile flip.
Code is executed as I see in the console, but it looks like click on wrong elements is fired.

I have custom directive with link method:

link: function (scope, element, attrs) {
            scope.hideClicked = true;
            scope.showClicked = false;

            scope.backClicked = function () {
                console.log('show front')
                scope.hideClicked = false;
                scope.showClicked = true;
            }

            scope.frontClicked = function () {
                console.log('hide front');
                scope.hideClicked = true;
                scope.showClicked = false;
            }
        console.log(scope, element, attrs);
    }

and in the template

<div class="tile" ng-class="{'hide-elem': hideClicked,'show-elem': showClicked }"> 
    <span class="front" ng-click="frontClicked()">{{itemData.value}}</span> 
    <span class="back" ng-click="backClicked();"></span> 
</div>

Full code to reproduct is here: https://codepen.io/lkurylo/pen/Laprjx

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Both child-span-Elements use absolute positioning, so it seems as if the browser decides that the second element is displayed “on top” of the first. As a result, the click only registers on the back-Element, which happens to be the top-element.

I suggest you display only one element at any given time, e.g. by adding ng-show or ng-if to both elements.

<span class="front" ng-if="showClicked" ng-click="..."></span>
<span class="back" ng-if="hideClicked" ng-click="..."></span>

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply