"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Detect Changes in DIV Height or CSS Attributes with jQuery?

How to Detect Changes in DIV Height or CSS Attributes with jQuery?

Published on 2024-11-09
Browse:624

How to Detect Changes in DIV Height or CSS Attributes with jQuery?

Determining Changes in DIV Height or CSS Attributes

When working with web pages, it's often necessary to track changes in the height or other CSS attributes of elements. jQuery provides various options to address this need.

Event Tracking with 'change()':

While the 'change()' event is primarily used for input elements, it can be customized to detect CSS changes. However, this approach involves periodically checking the element's CSS properties and triggering an event if they differ from the previous values:

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

    setTimeout(checkForChanges, 500);
}

Custom Event Binding with 'bind()':

A more efficient solution involves creating a custom event and binding it to the desired element:

$('#mainContent').bind('heightChange', function(){
        alert('xxx');
    });


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

In this case, we trigger the 'heightChange' event whenever the height of the 'mainContent' div is altered.

Note:

  • The frequency of checks in the 'checkForChanges()' function can be adjusted to suit specific requirements.
  • The 'bind()' and 'trigger()' methods are well-documented in the jQuery documentation for further reference.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3