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

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

Barbara Streisand
Release: 2024-11-04 00:25:03
Original
309 people have browsed it

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:

<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

Custom Event Binding with 'bind()':

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

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


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

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.

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