Home > Web Front-end > CSS Tutorial > How to Detect CSS Changes, Particularly Height Changes, Using jQuery?

How to Detect CSS Changes, Particularly Height Changes, Using jQuery?

Barbara Streisand
Release: 2024-11-03 11:20:02
Original
378 people have browsed it

How to Detect CSS Changes, Particularly Height Changes, Using jQuery?

How to Detect CSS Changes using JQuery

JQuery does not have a built-in event for detecting changes in CSS attributes. However, you can create your own using the following approaches:

Continuous DOM Monitoring (First Way):

Poll the DOM periodically (e.g., every 500 milliseconds) to compare the current CSS attribute value to the previous value. If they differ, trigger an event.

Example:

<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);
}

checkForChanges();</code>
Copy after login

Manual Event Triggering (Second Way):

Bind a custom event handler to the target element, and then manually trigger this event whenever you change the element's CSS.

Example:

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

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

Determining Height Changes Specifically (Solution for Initial Problem):

In the specific case of detecting height changes for the #mainContent div, use the second approach with the following code:

<code class="javascript">$('#mainContent').bind('heightChange', function () {
    $("#separator").css('height', $("#mainContent").height());
});</code>
Copy after login

Remember to bind the event handler before making any height changes to the #mainContent div.

The above is the detailed content of How to Detect CSS Changes, Particularly Height Changes, Using 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