How can I add an onload
event listener to the <body>
element (or some other suitable near-top-level element) in an HTML document via JavaScript?
I want to achieve the same behavior as this:
<body onresize="handleResize();">
...
</body>
(i.e., when the page resizes, the function should run)
But I want to add the event listener with JavaScript like this
(function() {
//effectively private because it's in the closure
function handleResize() {
//do stuff here
}
element.addEventListener("resize",handleResize);
})(); //IIFE
The problem I'm having is that I don't know how to grab the appropriate element to attach the event to.
I tried this:
document.documentElement.addEventListener("resize",handleResize);
And this:
document.body.addEventListener("resize",handleResize);
But in both cases, the handleResize
function never gets called.
How can I access the appropriate top-level or near-top-level element?
How can I add an onload
event listener to the <body>
element (or some other suitable near-top-level element) in an HTML document via JavaScript?
I want to achieve the same behavior as this:
<body onresize="handleResize();">
...
</body>
(i.e., when the page resizes, the function should run)
But I want to add the event listener with JavaScript like this
(function() {
//effectively private because it's in the closure
function handleResize() {
//do stuff here
}
element.addEventListener("resize",handleResize);
})(); //IIFE
The problem I'm having is that I don't know how to grab the appropriate element to attach the event to.
I tried this:
document.documentElement.addEventListener("resize",handleResize);
And this:
document.body.addEventListener("resize",handleResize);
But in both cases, the handleResize
function never gets called.
How can I access the appropriate top-level or near-top-level element?
Share Improve this question edited Apr 10, 2015 at 20:57 Sildoreth asked Apr 10, 2015 at 16:42 SildorethSildoreth 1,9151 gold badge25 silver badges41 bronze badges 1-
window.addEventListener("resize",handleResize);
usually does the trick.window
is also the topmost object you can add an onload handler. – Teemu Commented Apr 10, 2015 at 16:46
1 Answer
Reset to default 12Use the window element.
window.addEventListener("resize",handleResize,0);