1

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>
Ouroborus
  • 16,237
  • 4
  • 39
  • 62
  • Is there a parent event of some sort that's using it's event? Is the event tied to the button click? iirc `event` should be undefined because it isn't implicitely passed to the callback – Sterling Archer Feb 15 '17 at 21:41
  • Now that I know what I'm looking for, MDN's article on [window.event](https://developer.mozilla.org/en-US/docs/Web/API/Window/event) gives the details. – Ouroborus Feb 15 '17 at 21:52

2 Answers2

1

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.

thesublimeobject
  • 1,393
  • 1
  • 17
  • 22
1

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

Community
  • 1
  • 1
Colm Seale
  • 179
  • 6