Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the event object is undefined in my case

When click on a button, I want to get the event object e in the modern browsers like Firefox, Chrome,etc. the problem is when click on the button give me an undefined event object, note that when use window.event in internet explorer browser gets the event object.

// the Object
var countdown = {
    hours: 0,
    minutes: 0,
    seconds: 0,
    element_h: null,
    element_m: null,
    element_s: null,
    init: function (hElemId, mElemId, sElemId) {
        this.element_h = document.getElementById(hElemId);
        this.element_m = document.getElementById(mElemId);
        this.element_s = document.getElementById(sElemId);
    },
    play: function (e){
        alert(e.target);
    }
};

HTML:

<button onclick="countdown.play();">Play</button>
like image 789
Lion King Avatar asked Dec 09 '22 05:12

Lion King


1 Answers

You have to explicitly pass the event object to the onclick handler, like this

<button onclick="countdown.play(event);">Play</button>

Quoting MDN's Event Registration Doc page,

The JavaScript code in the attribute is passed the Event object via the event parameter.

When you register an event handler inline, it can be given the Event object with the event parameter. This will not be done automatically though. That is why we have to explicitly pass the event object. Since you didn't pass it, e is undefined by default.

like image 150
thefourtheye Avatar answered Dec 23 '22 07:12

thefourtheye