MShack
MShack

Reputation: 652

How to detect if a div has a scrollbar?

I'm trying to determine if a div has a scrollbar and then remove that div.
Not sure what I'm doing wrong here but I'm not able to detect it.

Jsfiddle: https://jsfiddle.net/cyj2sb0g

(function($) {
    $.fn.hasHorizontalScrollBar = function() {
        return this.get(0) ? this.get(0).scrollWidth > this.innerWidth() : false;
    }
})(jQuery);

if($(".ls-boxscore").hasHorizontalScrollBar()){
    $(this).remove();
}

Upvotes: 1

Views: 82

Answers (2)

Azhr-M
Azhr-M

Reputation: 286

You can try this code. also you can achieve with adding ID to an element. using id you don't need to go into element[0]

(function($) {
    $.fn.hasScrollBar = function() {
        var attrClass = $(this).attr("class");
        var elmnt = document.getElementsByClassName(attrClass);
        return elmnt[0].scrollWidth > this.width();
    }
})(jQuery);


$(function(){
    var scrollBarFound = $('.ls-boxscore').hasScrollBar();
    if(scrollBarFound) {
        console.log('scrollbarfound');
        $('.ls-boxscore').remove();
    }
});

Upvotes: 1

mx0
mx0

Reputation: 7143

Your hasHorizontalScrollBar function is working fine.

Inside if block this doesn't point to that div but to window object, change it to:

if($(".ls-boxscore").hasHorizontalScrollBar()){
    $(".ls-boxscore").remove();
}

Upvotes: 1

Related Questions