Reputation: 16875
I ran into a weird situation debugging somebody's code. The code below is a demonstration of the issue.
My impression is that event
should be undefined
when entering the event handler. It's like that in Firefox but in Chrome and IE11 event
is not undefined
, instead containing the event object. My guess is that a closure is in effect somehow but not when in Firefox.
Which way is it supposed to work? Where does the blame for the inconsistency lie (jQuery? Firefox? Chrome/IE11?)?
$('button').on('click',function(){
var color = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
$(event.target).css({backgroundColor:color});
$('body').css({backgroundColor:color});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button">Click me!</button>
Upvotes: 1
Views: 71
Reputation: 179
This seems like a duplicate of this question: ReferenceError: event is not defined error in Firefox
Basically Chrome, IE and Safari have a global symbol for events, Firefox doesn't. As best practice, you should always provide the paramter event
or e
or whatever
to normalize behaviour between browsers
Upvotes: 1
Reputation: 1403
In some browsers the event is actually globally defined, window.event
, which just refers to the last event. In others, it needs to be explicitly passed. You can always pass it as the first argument I believe (I know I ran into this not that long ago and think this is the solution I used).
If you want to be really safe, you could always pass it and then do event = event || window.event
inside the function.
Upvotes: 1