Home > Web Front-end > CSS Tutorial > How Can I Trigger an Event in jQuery When a CSS Class Changes?

How Can I Trigger an Event in jQuery When a CSS Class Changes?

Barbara Streisand
Release: 2025-01-01 06:13:16
Original
167 people have browsed it

How Can I Trigger an Event in jQuery When a CSS Class Changes?

Eliciting Events upon CSS Class Alterations in jQuery

Challenge:
Can jQuery be used to trigger an event when a CSS class is added or modified? Does altering a CSS class automatically invoke the jQuery change() event?

Resolution:
jQuery does not inherently offer an event for when a CSS class changes. However, you can trigger your own event using a trigger when altering a class in your script:

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

Then, bind your custom event to a selector to specify the actions to be taken when the class changes:

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

The change() event in jQuery is dedicated to input elements and triggers only when focus leaves an input with altered content after data entry.

Demonstration Code:

$(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

The above is the detailed content of How Can I Trigger an Event in jQuery When a CSS Class 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