jquery – What is the difference between on.click and click?

Question:

Well that, what is the difference between the two methods? Is it semantically the same or does it affect something?

$('#demo').on('click', function() {
  alert('Click con on.click');
});

$('#demo2').click(function() {
  alert('Click con click');
});
#demo{
  background-color:#F2F2F2;
  width:500px;
  height:100px;
  text-align:center;
  vertical-align: middle;
  display:table-cell;
  cursor:pointer;
}

#demo2{
  background-color:#E6E6E6;
  width:500px;
  height:100px;
  text-align:center;
  vertical-align: middle;
  display:table-cell;
  cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="demo">Click con on.click</div>
<div id="demo2">Click con click</div>

Answer:

Perhaps the most important difference is that .on('click', selector, function(){}) allows you to work with added elements after the DOM has been loaded, whereas with .click(function(){}) this does not it's possible.

$('#test1').on('click', '.demoOnClick',function() {                  
  console.log('Click con on.click');
});

$('.demoClick').click(function() {
  console.log('Click con click');
});

$('#crearBoton').click(function() {
  $('#test1').append('<div class="demoOnClick">Clic para On.click</div><div class="demoClick">Clic para .click</div>');
});
#crearBoton {
  border: solid 1px;
  cursor: pointer;
  width: 100px;
}

.demoOnClick {
  border: solid 1px blue;
  margin: 5px;
  padding: 5px;
}

.demoClick {
  border: solid 1px red;
  margin: 5px;
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test1">
  
  </div>
<div id="crearBoton">Clic aqui</div>

Other differences:

  • .on() creates a single handler for all the elements included in the selector, while .click() creates a single handler for each of these elements.
  • on() allows the use of namespaces.
Scroll to Top