Event listeners comparison - $().click, addEventListener, onclick (v22)

Revision 22 of this benchmark created on


Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div>Test</div><div>Test</div><div>Test</div><div>Test</div>

Setup

divs = document.getElementsByTagName('div');
    length = divs.length;
    for(var i = 0; i < length; i++){
      $(divs[i]).unbind().prop("onclick", null);
    }

Test runner

Ready to run.

Testing in
TestOps/sec
$().click anon
for(var i = 0; i < length; i++){
  $(divs[i]).click(function(){
    console.log('hi');
  });
}
ready
addEventListener anon
for(var i = 0; i < length; i++){
  divs[i].addEventListener('click', function(){
    console.log('hi');
  });
}
ready
onclick anon
for(var i = 0; i < length; i++){
  divs[i].onclick = function(){
    console.log('hi');
  };
}
ready
$().click
var f = function (){
  console.log('hi');
}

for(var i = 0; i < length; i++){
  $(divs[i]).click(f);
}
ready
addEventListener
var f = function (){
  console.log('hi');
}

for(var i = 0; i < length; i++){
  divs[i].addEventListener('click', f);
}
ready
onclick
var f = function (){
  console.log('hi');
}

for(var i = 0; i < length; i++){
  divs[i].onclick = f;
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.