4

I'm trying to trigger event on a <A> element with mousedown event handled by addEventListener call but I don't know why it doesn't work.
I tried to use angular.element(el).triggerHandler('click'); but it only triggers event handler specified via ng-click.

In the code below when I click on 'trigger' link only 'first' is printed to console. How do I make it print 'zero' as well?

JSBin link

HTML:

<a id='zero' href="#">zero</a><br/>
<a id="first" href="" ng-click="firstLinkClick()">first</a>
</br>
<a id="trigger" href="" ng-click="triggerLinkClick()">trigger</a>

Javascript:

document.getElementById('zero').addEventListener('click', function() {
  console.log('zero');
}, false);

app.controller('myCtrl', function myCtrl($timeout, $scope) {
  $scope.firstLinkClick = function() {
    console.log('first');
  };

  $scope.triggerLinkClick = function() {
    $timeout(function() {
      var el = document.getElementById('zero');
      angular.element(el).triggerHandler('click');
    }, 100);

    $timeout(function() {
      var el = document.getElementById('first');
      angular.element(el).triggerHandler('click');
    }, 100);
  };
});
3
  • bind the click event to #zero with angularjs as well. just like you did with the other two. why you need to do it outside of angular? Commented Jan 15, 2016 at 5:18
  • @Amir: #zero is an element generated by 3rd library so I can't change it. I want to simulate user behavior to click on it. Commented Jan 16, 2016 at 1:31
  • @georgeawg: Thank you for the information, but I'm not sure how it will solve my problem? Could you give an example? Commented Jan 16, 2016 at 1:33

1 Answer 1

4

Angular uses jqLite internally. If you load jQuery before Angular it will use jQuery instead of jqLite.

triggerHandler only triggers events that are added by jqLite/jQuery.

To trigger events added by addEventListener you need to use the standard API.

For example:

var el = document.getElementById('zero');
el.click();

Or:

var el = document.getElementById('zero');
el.dispatchEvent(new Event('click'));

If you need to support older browsers you can start by reading here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.