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
Release: 2024-11-05 09:42:02
Original
429 people have browsed it

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>
Copy after login

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>
Copy after login

You can use it as follows:

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

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template