Home > Web Front-end > CSS Tutorial > How to Detect Changes in Div Height or CSS Attributes in jQuery?

How to Detect Changes in Div Height or CSS Attributes in jQuery?

Patricia Arquette
Release: 2024-11-04 02:21:30
Original
811 people have browsed it

How to Detect Changes in Div Height or CSS Attributes in jQuery?

Detecting Div Height or CSS Attribute Changes in jQuery

Triggering Events on CSS Changes

jQuery natively lacks a specific event handler for CSS attribute changes, including height modifications. However, there are two approaches to address this problem:

Approach 1: DOM Element Monitoring

Regularly inspect the DOM element for CSS changes at a predefined interval (e.g., 500 milliseconds).

<code class="javascript">var $element = $("#elementId");
var lastHeight = $("#elementId").css('height');
function checkForChanges()
{
    if ($element.css('height') != lastHeight)
    {
        alert('xxx');
        lastHeight = $element.css('height'); 
    }

    setTimeout(checkForChanges, 500);
}</code>
Copy after login

Approach 2: Custom Event Triggering

Bind a custom event handler ('heightChange' in the example) to the element. Trigger the event whenever you modify its CSS.

<code class="javascript">$('#mainContent').bind('heightChange', function(){
        alert('xxx');
    });


$("#btnSample1").click(function() {
    $("#mainContent").css('height', '400px');
    $("#mainContent").trigger('heightChange'); //<====
    ...
});    </code>
Copy after login

The second approach is recommended if you have control over CSS changes, as it's more efficient and elegant.

Documentation:

  • bind: Attach an event handler to an element.
  • trigger: Execute all event handlers for a specified event type.

Note:

There was an outdated DOMAttrModified mutation event that allowed for tracking CSS changes, but it's no longer recommended.

The above is the detailed content of How to Detect Changes in Div Height or CSS Attributes in jQuery?. 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