views:

323

answers:

3

Is there a way to detect when a div shows or hides a scrollbar? When the scrollbar is showing, I want to resize some controls inside the div, so that the scrollbar won't cover them up.

So, I need an event that fires when the scrollbar appears and dissapears. Thanks, Brian

+2  A: 

You could wrap the content in another DIV - then you could detect the height of the content, and resize it if it's taller than the containing DIV. An example with jQuery:

if($('#content-wrapper-div').height() > $('#scrolling-div').height())
{
    var oldWidth = $('#content-wrapper-div').width();
    $('#content-wrapper-div').css('width', (oldWidth - 20) + 'px')
}

The '20' could be changed depending on the width of the scrollbar (or you could use height, or resize individual controls in there).

Mark B
+1  A: 

Seems like a lot of work for 20px. You may want to reconsider your design. But I'll bite.

There is no "elementGotBigger" event so to detect that you'd need to know before what user interactions could cause that:

  1. DOM ready
  2. Window Resize
  3. Some other event you know could cause the change (maybe a navigation piece)

Then have each of those events fire a function that checks

  1. The size of the element compared to
  2. The scroll size of the element.

Then if the scroll size is greater than the size of the element, do stuff.

Here's an example with mootools: http://mooshell.net/HC3g9/

rpflo
Doesn't work properly in Safari 4 on Mac OS X 10.6. It still says "false" when the scrollbar appears until it is shrunk even more at which point it says "true".
titaniumdecoy
lol onclick=elementGotBigger. Nicely put.
corymathews
@titaniumdecoy: it could use some pruning, but the concept is there. I still think it's a design flaw, however. Just give the control view 20 more pixels to start with.
rpflo
I have Telerik RadPanelItem controls inside this scrolling area. If I shrink them to make room for the scrollbar to appear, then a white space is shown to their right. If I make them full size, then when the scrollbar appears, it covers up the right hand side of the controls. I wound up setting the container div to always show the scrollbar (overflow-y: scroll). I then added a div inside of it that I can use to get the width of and resize my other controls.Thanks,Brian
BrianK
Forcing a scroll bar makes a lot of sense. Glad you found something that works. Reading my comments I sound a bit uppity about the design suggestions. I apologize, I'm often on SO late at night when brain no work good.
rpflo
A: 

Your question intrigued me, and I wasn't thrilled with the other answer (no offense, seemed hacky), although it may work. In googling A Better Way, I stumbled upon this jQuery plugin. Using something like this would be good because different browsers may render the scrollbar in different widths.

Barnabas Kendall