1

I'm looking to add a class to an element but only if the content requires the user to scroll.

The element in question responds to screen size, and so it will only require the user to scroll on smaller screen sizes. I'd like to add different styles to the element in that case only and not when the content fits without scrolling.

I'm unsure how to do this but I'm confident there will be a js/jquery solution out there somewhere!

Mr DC
  • 33
  • 5

3 Answers3

1

For a given element let's say with an id "MyId" you can do this :

if ( $('#MyId')[0].scrollHeight > $('#MyId').innerHeight() )
{
    $('#MyId').addClass('myClass');
}

Explanation :

  • scrollHeight

this is the height of an element's content including what's not visible due to overflow.

  • innerHeight

this is the actual height of the element content, including top and bottom padding, and taking into account horizontal overflow.

as opposed to

  • clientHeight

which is the same but doesn't take into account horizontal overflow.

zoubida13
  • 1,738
  • 12
  • 20
1

Something like this should work. Basically you check if element's actual height is bigger than just it's visible height.

if($(element).innerHeight() < $(element)[0].scrollHeight) {
    $(element).addClass('scrollable-div');
}
Mario Plantosar
  • 804
  • 9
  • 24
  • this will not work if the element has padding – zoubida13 May 16 '16 at 12:56
  • this will now work except it's exactly the same as my answer :D – zoubida13 May 16 '16 at 13:12
  • Your point being? You answered about 10 seconds before me, and you edited your answer afterwards as well. Plus you don't have any explanation on how it works. You should always explain how your answer works in order for it to bring value to future readers as well as OP. – Mario Plantosar May 16 '16 at 13:18
  • I didn't mean it in a bad way, you did explain it better, I was just being cheeky, no offense! I upvoted you for not calling me a git :) – zoubida13 May 16 '16 at 13:21
  • No worries, upvoted your answer too, just edit in some quick explanation and OP should definitely choose your answer. – Mario Plantosar May 16 '16 at 13:23
0

Just add a .scroll function, it won't function if you don't scroll.

$(window).scroll(function() {    
    var scroll = $(window).scrollTop();
    if (scroll >= 0) {
        // do something
    }

});
Gavin Thomas
  • 1,196
  • 6
  • 10