Home > Web Front-end > CSS Tutorial > How to Create a Custom Event to Track CSS Attribute Changes?

How to Create a Custom Event to Track CSS Attribute Changes?

Susan Sarandon
Release: 2024-11-03 07:27:30
Original
599 people have browsed it

How to Create a Custom Event to Track CSS Attribute Changes?

Custom Event to Track CSS Attribute Changes

Problem: How can you trigger an event when a div or any CSS attribute changes?

Discussion: While there is no built-in CSS change event, you can create your own. There are two methods:

Method 1: DOM Polling

<code class="javascript">var $element = $("#elementId");
var lastHeight = $("#elementId").css('height');

function checkForChanges() {
  if ($element.css('height') != lastHeight) {
    // CSS height changed
    lastHeight = $element.css('height');
  }
  setTimeout(checkForChanges, 500);
}
checkForChanges();</code>
Copy after login

Method 2: Manual Event Trigger

<code class="javascript">$('#mainContent').bind('heightChange', function() {
  // CSS height changed
});

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

Advantages:

  • Method 1 is automatic, monitoring the DOM for changes constantly.
  • Method 2 is more controlled, triggering the event only when you modify the CSS.

Documentation:

  • bind: Attaches an event handler to the specified element.
  • trigger: Executes event handlers attached to an element.

The above is the detailed content of How to Create a Custom Event to Track CSS Attribute Changes?. 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