Home >Web Front-end >CSS Tutorial >How to Detect Changes in Div Height or CSS Attributes 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:
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>
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>
The second approach is recommended if you have control over CSS changes, as it's more efficient and elegant.
Documentation:
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!