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

1

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

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

or

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

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

  • If there is any difference in memory, processing and performance between these two variations
  • If there is any other difference between them, in addition to the above.
  • Or even, if there is any reason why I choose to choose one of the two alternatives.
  • asked by anonymous 30.03.2017 / 16:32

    1 answer

    0

    The basic difference between the two is where you tie the click event.

    In the first case it will capture the event when it arrives at body and has origin in the desired selector. As events in javascript propagate, when the user clicks the selector it will propagate up to body and you will capture correctly.

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

    And what is the advantage of linking body ? When you do this, there is no need for the element to exist on the page. This is extremely useful when you create the element dynamically. You can bind the event to it without necessarily having created the element yet.

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

    The click on the button will fire the function carregaItems

    In the second case, you rely on the element to be present on the page to bind the event to it. If the code that runs the event runs before the code that creates the element, the element goes unheard in the event.

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

    The% wont of the button will not trigger the click function because the carregaItems of the event is made on an element that does not exist in bind yet.

        
    30.03.2017 / 16:39