Detect when window vertical scrollbar appears

Roman picture Roman · Feb 1, 2010 · Viewed 44.3k times · Source

Is there a simple and reliable solution for detecting window vertical scrollbar appears/disappears?

window.onresize isn't triggered when after JavaScript DOM manipulation page becomes high enough for appearing scrollbar.

In this very similar post Detect if a page has a vertical scrollbar described solution how to detect whether scrollbar is present or not, but I need to know when exactly it appears.

Answer

OrganicPanda picture OrganicPanda · Jan 2, 2014

Sorry to bring this back from the dead but I have just run in to this limitation and came up with my own solution. It's a bit hacky but stick with me ...

The idea is to add a 100% width invisible iframe to the page and listen for resize events on it's internal window. These events will pick up changes not only to the outer window's size but also when scrollbars get added to or removed from the outer window.

It triggers a regular window resize event so it requires no extra code if you are already listening for window resize.

Tested in IE9 and Chrome/Firefox latest - could maybe be made to work in older IEs but my project doesn't support those so I haven't tried.

https://gist.github.com/OrganicPanda/8222636