Detecting horizontal scrolling and div’s with overflow:auto

May 7th 2012 - Code

What I was trying to figure out is how can you check if a table (or a div) that has a parent div with CSS overflow:auto applied to it and has started to horizontally scroll with JavaScript/jQuery.

Seems that the scroll() API in jQuery only checks if the event has been triggered and not if it has a visible scroll.

Then I found element.scrollWidth. All I had to do is check if the scroll width is greater than the container width[1. This is so simple but took me ages to figure out.] and BOOM. Pretty simple when you think about it 🙂

HTML

Lorem ipsum adhuc maiestatis
dolor sit amet, meis solum eam ea, e has ea, alii ipsum necessitatibus ex qui.

CSS

table { border : 1px solid red; white-space: nowrap; width: 100%;}
div { border: 1px dashed blue; padding: 10px; overflow: auto; }

JavaScript

    window.onresize = function() { 
         if ( $("div").outerWidth() < $("div").get(0).scrollWidth ) {
             console.log("foo bar scrollbar");
         } else {
             console.log(" no scrolling :)  ");
         }
     };

Bare in mind that you will need to use a browser that supports log commands to get the scroll message. IE9 and above supports it in the dev tools as does Firebug & Chrome.