JavaScript for WordPress Forums Vanilla JavaScript Lesson 1.4.3 – Global event handlers

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #27512
    bruno
    Participant

    I have a quick questions on this one:

    I understand that we can call a “global event handler” via 2 ways:
    referencing a function linke
    element.onclick = myFunc;

    and directly on the event link
    element.onclick = function ( event ) { }

    My question is regarding to when we reference the function, let´s say that we have something like this:

    var myFunc = function( event ) {
       something here...
    }
    
    element.onclick = myFunc;

    When we create the function expression we are setting the function with the parameter event, so how this parameter is passed when we do:
    element.onclick = myFunc;?

    I don´t fully understand what is going on in this line, how the event is passed? it´s something that the property onclick do?

    #27529
    Zac Gordon
    Keymaster

    GREAT Question!

    This is due to the magic that browsers, or the engines they use, bring to the table.

    Chrome, for example, automatically makes the event object available for you to use with the name ‘events’ in a function hooked up to an event this way.

    Firefox on the other hand does it a little differently and makes it available as the first value in an arguments array that it passes to functions hooked to events. So you could do this for Firefox:

    
    var myFunc = function() {
       eventObj = arguments[0];
    }
    
    element.onclick = myFunc;
    

    For this reason you may sometimes see some code like this checking to see which approach is being taken and assigning that to a variable called events. This will work for Chrome or Firefox (and most other browsers).

    
    var myFunc = function() {
       eventObj = arguments[0] || events;
    }
    
    element.onclick = myFunc;
    

    The most common solution though is just to assign whatever is being automatically passed into your function with the name ‘events.’ You can do that this way:

    
    var myFunc = function( event ) {
      console.log( event );
    }
    
    element.onclick = myFunc;
    

    This way whether ‘events’ is passed or ‘arguments[0]’ it is still made available as events.

    So folks prefer naming it ‘e’ to avoid confusing it with the native name something like Chrome would use.

    
    var myFunc = function( e ) {
      console.log( e );
    }
    
    element.onclick = myFunc;
    

    Hope that explains things a little better!!!

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.