1

I have to check if a div(scrollApplist) has scrollbar enabled. If scrollbar is visible, small margin will be applied. If scrollbar is not visible, large margin will be applied(Scrollbar height is added dynamically)

<div id="scrollApplist" [ngStyle]="{ height: scrollBarHeight }" class="cardlistScrollBar"> 
<div  [ngClass]="this.isScrollBarVisible?'smallMarginRight':'largeMarginRight'">
<card-list [cardItems]="records"></card-list>
</div>
</div>
.cardlistScrollBar{
    overflow-y: auto;
    border-radius: 4px;
    line-height: normal;
}

As per this document How can I check if a scrollbar is visible?, I checked scrollHeight and clientHeight of this div scrollApplist.

function scrollbarVisible(element) {
  return element.scrollHeight > element.clientHeight;
}

Using this condition :

document.querySelector('#scrollApplist').scrollHeight > document.querySelector('#scrollApplist').clientHeight

But scrollHeight and clientHeight are same on the first load(When first time rendering the application) even if scrollbar is visible. All other cases, it is working fine. How to resolve this issue?

smilyface
  • 5,021
  • 8
  • 41
  • 57
Surya K S
  • 19
  • 3
  • Maybe compare clientWidth with offsetWidth as [explained here](https://www.javascripttutorial.net/dom/css/get-the-scrollbar-width-of-an-element/). I'm guessing scrollbar present is > 0, and not-present will make the difference be 0 – Francisco Santorelli Nov 01 '22 at 14:00
  • @FranciscoSantorelli Tried this. clientWidth and offsetWidth are also same on first rendering – Surya K S Nov 01 '22 at 15:03
  • @SuryaKS - when is the function ‘scrollbarVisible’ is called? Onload? Can you try: window.onload = function() { yourFunction(param1, param2); }; – smilyface Nov 03 '22 at 13:58
  • All other cases means what else cases it is working? – smilyface Nov 03 '22 at 14:00
  • @smilyface function ‘scrollbarVisible’ is called from ngOnInit. Other working scenarios : If we resize the window or adding any new records in the cardlist , scrollHeight will be greater than clientHeight.(Like after performing any action, it will work) – Surya K S Nov 03 '22 at 15:53
  • window.onload = function() { yourFunction(param1, param2); }; Tried this. Not working – Surya K S Nov 03 '22 at 15:54
  • Got it. Tried setting min-height and min-width for your div? (In Default this property should be loaded) – smilyface Nov 03 '22 at 17:26
  • 1
    @smilyface I can't set max-height ,min-height for this div since the height needs to be changed dynamically – Surya K S Nov 04 '22 at 05:18

1 Answers1

0

if you can use jquery in your project then the below code can fulfill your requirement.

$(function() {
    alert('div1:' + $('#divElement1').hasScrollBar());
});

(function($) {
    $.fn.hasScrollBar = function() {
        return this.get(0).scrollHeight > this.height();
    }
})($);

replace the #divElement1 with the element id which you wanted to check scrollbar is present or not.

Thank you.

TheMrK
  • 11
  • 1