How events work in jquery

1

I'll show examples of just the click event to make it simpler to explain, but this question is about any jquery event.

When I started using jquery I only used the click event as follows:

$("button").click(function(){
  alert('ok');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><button>Confirmar</button>

Thatworkedfine,butthenIstarteddoingthefollowing:

$("#area").html($("<button/>").text('Outro botão'));

//Primeira forma
$("button").click(function(){
  alert('ok 1');
});

//Segunda forma
$("button").on('click', function(){
  alert('ok 2');
});

//Terceira forma
$('#area').on('click', 'button', function (event) {
    event.preventDefault();
    alert('ok 3');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><button>Confirmar</button><divid="area"></div>

I put two more examples, the "second form" I started to use because I noticed that sometimes when I created an element dynamically with jquery the "first way" to use the click event did not work, I used this form for a good time, until one day it also did not work then discover the "third way" and so I can put the event click on any element without problems.

But my "technique" is as follows, I try the first, it does not work I go to second and in turn it did not work step to third.

What I want to know is why, this is a feature of jquery, it's because of javascript because sometimes it works and because sometimes it does not work, that's what I wanted to know, I use events but I do not I know the reason for this behavior.

    
asked by anonymous 15.05.2018 / 22:22

1 answer

2
The first is a shortcut to $("button").on('click', function(){

$("button").click(function(){
  alert('ok 1');
});

You can check in the source of the official repository alias.js#L10 , this:

jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " +
    "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
    "change select submit keydown keypress keyup contextmenu" ).split( " " ),
    function( i, name ) {

    // Handle event binding
    jQuery.fn[ name ] = function( data, fn ) {
        return arguments.length > 0 ?
            this.on( name, null, data, fn ) :
            this.trigger( name );
    };
} );

See that you have this.on( name, null, data, fn ) , .trigger is only executed if you do not pass function , do this for example $("...").click(); , which is used to trigger the event.

The second is the "default", and you can also create your own events by using .trigger

$("button").on('click', function(){
  alert('ok 2');
});
The third form is actually event delegation, click occurs in #area , but event is only triggered if element that triggered click in #area "match" to query of second parameter, ie button

$('#area').on('click', 'button', function () {
    alert('ok 3');
});

The advantage of the third party over others is that you would not have to use things like $.ready or $(window).load to set the click event on the button, it already recognizes if the button exists in #area , since the check of delegation only occurs at the time of the click

  
  • The first way to use the click event did not work

  •   
  • What I want to know is why, this is a feature of jquery, it's because of javascript, because sometimes it works and because sometimes it does not work, that's what I wanted to know, I use the events but I do not know why this behavior.

  •   

    This was probably some confusion of your own, it's unlikely that .on('click') would work and .click no, since it's just a shortcut, the only possible possibilities, I believe, for having caused the crash would be:

    • A bug in the specific version of jQuery you are using
    • Some jQuery add-ons that affected your scripts
    • It was just some confusion of yours, maybe other events with stopPropagation or something similar that prevented it and you removed them when you switched to .on without realizing it.
      

    But my "technique" is as follows, I try the first, it does not work I go to second and in turn it did not work step to third.

    I personally would always choose the third one, it's simple, you do not need to check if the DOM exists, if you create a new element it will work, removing it will not have to do much if you need any element with a specific class or attribute on the page to have the event just use document , example:

    $(document).on('click', '#area button', function () {
        alert('ok 3');
    });
    

    Or so (in this case elements with classes foo and bar will trigger the event):

    $(document).on('click', '.foo, .bar', function () {
        alert('ok 3');
    });
    
        
    15.05.2018 / 22:52