0

I have a div in a view that I only want to show scrollbars for it if it overflows. I also want to show the borders, but only if it overflows.

I have the scrollbar part figured out using a CSS class

.conditional-scrollbars {
    overflow: scroll;
    overflow-y: auto;
    overflow-x: auto;
}

Is there a way to only show the div borders if it overflows?

Is there an event that fires when the scrollbars are made visible?

DanTheMan1966
  • 45
  • 1
  • 11
  • This doesn't seem possible with CSS alone: [CSS has-scrollbar selector? Target elements with visible scrollbars only](https://stackoverflow.com/questions/31114800/css-has-scrollbar-selector-target-elements-with-visible-scrollbars-only) – showdev Jan 09 '18 at 21:24
  • Possible duplicate of [How can I check if a scrollbar is visible?](https://stackoverflow.com/questions/4814398/how-can-i-check-if-a-scrollbar-is-visible) – showdev Jan 09 '18 at 21:25

2 Answers2

0

Building off of Adam's answer. You can add a border based on the height of the div. Here is the code I added from Adam's answer:

if ($('.conditional-scrollbars').height() >= 100) {
    $('.conditional-scrollbars').css('border', '2px solid #ddd')
}

You can remove the border in the same type of manner.

$('#addTxt').on('click', () => {
    $('.conditional-scrollbars').append('<p>Hello world!</p>');
 if ($('.conditional-scrollbars').height() >= 100) {
     $('.conditional-scrollbars').css('border', '2px solid #ddd')
    }
});
.conditional-scrollbars {
    overflow: scroll;
    overflow-y: auto;
    overflow-x: auto;
    max-width:100px;
    max-height:100px;
    
    /* for demo */
    min-width: 50px;
    padding: 2px;
}
p {
    margin:0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="conditional-scrollbars"></div>
<button id="addTxt">add text</button>
Anthony
  • 1,439
  • 1
  • 19
  • 36
0

I found something that worked. I added this function to a js file

// function to determine if an element has scrollbars 
(function ($) {
    $.fn.hasScrollBar = function () {
        return this.get(0) ? this.get(0).scrollHeight > this.innerHeight() : false;
    }
})(jQuery);

Then I just check the element after it has been populated. If the hasScrollBar function returns true, I add borders to the element via a css class.

DanTheMan1966
  • 45
  • 1
  • 11