hh54188
hh54188

Reputation: 15646

Javascript: bind scroll or resize event to which element is better?

I always see people bind scroll and resize event to window element

How about bind these event to document or document.documentElement even document.body elment?

Are there are some drawback?

Upvotes: 4

Views: 518

Answers (2)

Gromo
Gromo

Reputation: 1609

Resize event is supported only by window element, so binding it to any other element won't work. I'd like to be able to handle resize on any element, but there is no native event to bind on, so when I need handle resize I have to check element size every XXX ms.

From the other hand scroll event works on any element that can be scrolled. Both window and document can be scrolled and, looks like, both work the same way. <DIV> and any other element can be scrolled if it is block element with overflow:auto/scroll style and has content which size is bigger than container's size.

Sometimes you can bind scroll event to window and got nothing because scrolling is done in another element ;)

Upvotes: 1

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85575

There are mainly three DOM objects:

  • window
  • document
  • element

And each DOM objects has it's own different properties and methods. So the scroll and size properties are of window object and not of the document object.

So, use them with the window and not with the document.

Upvotes: 0

Related Questions