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>
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>
In this case, we trigger the 'heightChange' event whenever the height of the 'mainContent' div is altered.
Note:
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!