When browser's vertical scrollbar appears or disappears, the width of viewport or browser window changes (can be tested using jQuery's $(window).width() method), but window's resize event is not triggered. How come?
3 Answers
Re-size is an event that is driven by the actual browser window changing size.
What if I removed elements from my page until my content fit within the screen ? That's not a window re-size. Or if i change the overflow for the page to hidden. The scroll bars will disappear, however this again is not a re size.
What I am getting at is this: Scrollbar visibility does not necessarily mean that there was a re-size event.
-
If it's not a window resize, then why jQuery returns a different width for window? Commented Jan 31, 2013 at 16:04
Instead of resize, use overflowchanged event.
Browsers don't recognize it as resize. Then if you need "scrollbar appeared" and "scrollbar disappeared" events, use this code:
<div id="footerDiv" style="float: left; height: 1px; width: 100%;"></div>
bodywidth = 0;
$(document).ready(function () {
bodywidth = $("#footerDiv").width();
setInterval(scrollbarHelper, 100);
});
function scrollbarHelper() {
var newwidth = $("#footerDiv").width();
if (bodywidth !== newwidth) {
if (bodywidth > newwidth) {
alert("Scrollbar Appeared");
// Your code here
}
else if (bodywidth < newwidth) {
alert("Scrollbar Disppeared");
// Your code here
}
bodywidth = newwidth;
}
}