How jquery events work

Asked

Viewed 366 times

1

I will show examples only of the click event to be simpler to explain, but this is related to 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>

Which, by the way, worked really well, but then I started doing it this way:

$("#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>
<div id="area"></div>

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

But my "technique" is the following, I try the first, it does not work I go to second and in turn 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 doesn’t work, that’s what I wanted to know, I use events but I don’t know why this behavior.

1 answer

2


To 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 who has the this.on( name, null, data, fn ), the .trigger is executed only if it does not pass the function, do this for example $("...").click();, which is used to trigger the event.


To second is the "standard", and with it you can also create own events making use of the .trigger

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

To third form actually it comes to event delegation, the click occurs in the #area, but the event is only triggered if the element that triggered the click in #area "match" with the query of the second parameter, ie button

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

The advantage of the third over the others is that you wouldn’t need to use things like $.ready or $(window).load to set the event click on the button, it itself already recognizes whether there is a button on #area, since the verification of the delegation only occurs at the time of the click


  1. the "first way" to use the click event did not work

  2. 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 doesn’t work, that’s what I wanted to know, I use events but I don’t know why this behavior.

This was probably some mess of yours, it’s improbable that .on('click') functioned and .click no, since it’s only a shortcut, the only possible possibilities, I believe, of having caused the failure would be:

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

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

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

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

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

$(document).on('click', '.foo, .bar', function () {
    alert('ok 3');
});

Browser other questions tagged

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