4

I need to find a way to include hidden divs in the each statement below. I can't seem to find the answer. It's not just for children of a hidden element so i'm not able to write it based on display:none

$("div").each(function(){
    if ($(this).hasScrollBar()){
        $(this).addClass('scrollable');
    }
});

hasScrollBar Function:

(function($) {
    $.fn.hasScrollBar = function() {
        return this.get(0).scrollHeight > this.innerHeight();
    }
})(jQuery);
CoreyRS
  • 2,227
  • 3
  • 26
  • 44
  • it sounds like your issue has been over simplified in your explanation. Can you expand on the problem? – charlietfl Dec 27 '12 at 00:36
  • By `hidden`, do you mean `visibility:hidden`,`opacity:0`,`display:none` or some combination thereof? – Asad Saeeduddin Dec 27 '12 at 00:36
  • 1
    @CoreyRS `div`s with `display:none` are not excluded by the selector `"div"`, so I'm not sure what the problem is. – Asad Saeeduddin Dec 27 '12 at 00:39
  • @charlietfl what i'm trying to do is see if the child content of the hidden div causes it to have a scrollbar and if so add a class. This is being done on page load. – CoreyRS Dec 27 '12 at 00:42
  • 1
    `causes it to have scrollbar` ... you really need to provide more code and details. If you are using a plugin... show us how it works. WHere does `hasScrollbar()` come from for example – charlietfl Dec 27 '12 at 00:44
  • @CoreyRS the problem lies with your scrollbar function. You can't get the height of a hidden element. Look here: http://stackoverflow.com/questions/2345784/jquery-get-height-of-hidden-element-in-jquery – Jacob Raccuia Aug 18 '13 at 19:07

2 Answers2

8
$('div')         finds all divs
$('div:hidden')  finds only hidden divs
$('div:visible') finds only visible divs
gdoron
  • 147,333
  • 58
  • 291
  • 367
  • i know about using the hidden and visible selectors, which is why i specified `div` in the function, but it's only doing it for visible divs. I need it to be done for both. – CoreyRS Dec 27 '12 at 00:36
  • 1
    @CoreyRS, and so it will... as I answered(!) `$('div')` selects hidden divs as well... your problem lies some where else I'm afraid. – gdoron Dec 27 '12 at 00:40
0

You seem to be trying to identify all elements that would need scrollbars if they were displayed. One approach would be to make a clone of the element, render it offscreen, then figure out whether it needs scrollbars.

$("div").each(function(){
    var clone = $(this).clone();
    clone.show()
         .css('position','fixed')
         .css('left','-10000000');
    $(document).append(clone);
    if (clone.hasScrollBar()){
        $(this).addClass('scrollable');
    }
    clone.remove();
});
Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
  • thanks... i shall try this. It's for a mobile page so I must make sure it isn't so bloated that it slows down the page loading dramatically. – CoreyRS Dec 27 '12 at 01:34