admin管理员组文章数量:1244432
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);
本文标签: domHow to add event listener to body element via JavaScriptStack Overflow
版权声明:本文标题:dom - How to add event listener to body element via JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740223812a2244313.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论