Is event a global variable that is accessible everywhere inside the callback chain?

21,409

One can access the current event through window.event. Just using event is implicitly accessing window.event.

Share:
21,409
zanona
Author by

zanona

My primary focus over the past 15 years has been full-stack web development and implementation, experimenting with technologies while thinking openly about how tech and users can interact. Currently, acting as a web consultant for goal-oriented businesses and concentrating on designing interactive systems, UX research/ implementation and engineering/development of elaborate online platforms.

Updated on November 23, 2020

Comments

  • zanona
    zanona over 3 years

    I was just playing around with event listeners with DOM and Javascript and did notice this:

    function chained(msg) {
        console.log(msg, event);
    }
    
    function onClick() {
        chained('the body was clicked');
    }
    
    document.body.addEventListener('click', onClick);
    

    Now the funny thing...this will output:

    "the body was clicked, (MouseEvent)"

    Then I ask, why? how does it passes the event object without sending it on the chained call?

    function chained(msg) {
        console.log(msg, namedEventObj); //throw error namedEventObj is not defined
    }
    
    function onClick(namedEventObj) {
        console.log(event); //outputs (MouseEvent);
        console.log(nameEventObj); //outputs (MouseEvent);
        chained('the body was clicked');
    }
    
    document.body.addEventListener('click', onClick);
    

    Even If I declare the event obj to be passed on the onClick function as namedEventObj it will available only to onClick but not to chained function...I got this and this makes sense for me...but definitely not the event variable to be available to the chained function.

    Anyone know why does it behaves like this?

    The only thing I can think of is that event is in fact window.event and it makes itself available when some event dispatches and Event...but that would mean that any element could get that event information if called at the same time as the event when it triggers?

    I am using Chrome 11.0.x

  • kendotwill
    kendotwill almost 9 years
    @redgetan How do you use event in firefox?
  • alxndr
    alxndr over 8 years
    @kendotwill event handlers will be passed an object that is the event
  • U.P
    U.P almost 7 years
    @redgetan You Sir! are a life saver.