While debugging someone else's code, I encountered a puzzling situation. The snippet of code provided below illustrates the problem.
It seems to me that event
should be undefined
upon entering the event handler. This is indeed the case in Firefox, but in Chrome and IE11, event
contains the event object instead of being undefined
. I suspect that there might be a closure at play causing this difference in behavior between browsers.
Which behavior is the correct one? Who or what is responsible for this inconsistency (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>