Home >Web Front-end >JS Tutorial >How to Determine if a DIV Element Has a Visible Scrollbar?

How to Determine if a DIV Element Has a Visible Scrollbar?

Barbara Streisand
Barbara StreisandOriginal
2024-11-05 09:42:02444browse

How to Determine if a DIV Element Has a Visible Scrollbar?

Determining Scrollbar Visibility

Q: Checking for Overflow Auto in a DIV

Can you determine if a DIV element has its overflow property set to auto?

Example:

<code class="html"><div id="my_div" style="width: 100px; height: 100px; overflow:auto;" class="my_class">
  * content
</div></code>

In the provided JavaScript code snippet, you want to check if a scrollbar is visible within the DIV with the class "my_class" upon mouse hover.

A: Utilizing a Custom jQuery Plugin

To achieve this functionality, you can employ a custom jQuery plugin:

<code class="javascript">(function($) {
    $.fn.hasScrollBar = function() {
        return this.get(0).scrollHeight > this.height();
    }
})(jQuery);</code>

You can use it as follows:

<code class="javascript">$('#my_div1').hasScrollBar(); // Returns true if there's a vertical scrollbar, false otherwise.</code>

This method has been tested in Firefox, Chrome, and IE6-8.

Note: This plugin may not work correctly with the body tag selector.

Alternative Solution for Horizontal Scrollbars:

If a horizontal scrollbar causes a vertical scrollbar to appear, you can use this alternative method:

<code class="javascript">return this.get(0).scrollHeight > this.get(0).clientHeight;</code>

The above is the detailed content of How to Determine if a DIV Element Has a Visible Scrollbar?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn