Differences between $('body'). on('click',...) and $('selector'). click()

Asked

Viewed 631 times

1

I have a doubt in the declaration of click of an element with jQuery, I know I can do the following ways:

$('body').on('click', '...selector...', function () {...})

or

$('...selector...').click(function () {...})

I know the first way I don’t need to be giving rebind whenever a new element appears on my page, but would like to know:

  1. If there is any difference in memory, processing and performance between these two variations
  2. If there is any other difference between them , beyond the aforementioned.
  3. Or even, if there’s any reason why I should choose one of the two alternatives.
  • Related: http://answall.com/questions/5196/qual-a-diferen%C3%A7a-entre-o-onclick-Function-e-o-clickfunction

1 answer

0

The basic difference between the two is who you link the event to click.

In the first case it will capture the event when it arrives at the body and originate from the desired selector. As javascript events propagate, when the user clicks on the selector it will propagate to the body and you will capture correctly.

In the second you attach the event directly to the selector. When the click originates in it, you will capture the event.

And what is the advantage of linking to body? When you do this, it is not necessary for the element to exist on the page. This is extremely useful when you create the element dynamically. You can tie the event to it without necessarily creating the element yet.

$('body').on('click', '#botao', carregaItems);
var botao = $('<div id="botao">ola</div>');
$('body').append(botao);

The click on the button will trigger the function carregaItems

In the second case, you depend on the element to be present on the page to link the event to it. If the code that links the event is executed before the code that creates the element, the element is left unheard in the event.

$('#botao').click(carregaItems);
var botao = $('<div id="botao">ola</div>');
$('body').append(botao);

The click on the button nay will trigger the function carregaItems why is the bind event in an element that does not exist in the DOM yet.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.