最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

dom - How to add event listener to body element via JavaScript? - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 12

Use the window element.

window.addEventListener("resize",handleResize,0);
发布评论

评论列表(0)

  1. 暂无评论