Home > Web Front-end > CSS Tutorial > How Can I Trigger Events Based on CSS Class Changes in jQuery?

How Can I Trigger Events Based on CSS Class Changes in jQuery?

Linda Hamilton
Release: 2024-12-26 11:18:22
Original
489 people have browsed it

How Can I Trigger Events Based on CSS Class Changes in jQuery?

Triggering Events on CSS Class Modifications in jQuery

In jQuery, you may encounter the need to execute an event when a CSS class is either added or modified within an element. However, there is no inherent event that triggers upon a CSS class change.

Custom Event Solution

To address this, you can invoke a custom event using the trigger() function. When you modify the class with addClass(), you raise the custom event, which can then be bound to specific elements.

$(this).addClass('someClass');
$(mySelector).trigger('cssClassChanged');
Copy after login

In another part of the code, you can bind the custom event to a selector and define the actions to be executed when the class change occurs.

$(otherSelector).bind('cssClassChanged', data, function(){ do stuff });
Copy after login

Example Implementation

Consider the following code snippet:

$(function() {
  var button = $('.clickme')
      , box = $('.box')
  ;
  
  button.on('click', function() { 
    box.removeClass('box');
    $(document).trigger('buttonClick');
  });
            
  $(document).on('buttonClick', function() {
    box.text('Clicked!');
  });
});
Copy after login
.box { background-color: red; }
Copy after login
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="box">Hi</div>
<button class="clickme">Click me</button>
Copy after login

In this example, when the button is clicked, the "box" class is removed. This triggers the custom event "buttonClick," which changes the text of the div with the "box" class to "Clicked!"

The above is the detailed content of How Can I Trigger Events Based on CSS Class Changes in 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