Oliver Watkins Oliver Watkins - 6 months ago 13
Javascript Question

How to get the event source from calling element

I have an event listener in a list item :

<li class="item" ng-click="click($event)">
<a href="#/home">Home</a>
</li>


In my controller I have a click handler :

$scope.click = function($event) {
t2 = $($event.target.parentElement);
t2.addClass('clicked');
}


However, sometimes my $event.target is the list element, and sometimes it is the anchor element. This is because of where I click, sometimes it is on the a element but not on the list. Is there a way of getting from the event object the element that called the function?

Answer

Use $event.currentTarget

 $scope.click = function($event) {      
    t2 = $($event.currentTarget.parentElement);
    t2.addClass('clicked');

}

Comments