<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body {
height: 1000px;
}
</style>
<title>Scroll</title>
</head>
<body>
<button id="btn">click</button>
<script type="text/javascript">
document.body.onscroll = function() {
alert(this);// displays [object Window], instead of [object HTMLBodyElement]
};
document.getElementById('btn').onclick = function() {
alert(this);// displays [object HTMLButtonElement]
}
</script>
</body>
</html>
I put the this keyword in a button element event handler and in another handler of the body element, but the second this keyword referred to the global window object. Why?
That's because the body element exposes as event handler content attributes a number of the event handlers of the Window object.
Such events are, currently: blur, error, focus, load, resize and scroll.
This list is called "Window-reflecting body element event handler set".
(See, for example: https://html.spec.whatwg.org/dev/webappapis.html)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With