Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Detect class changes

Tags:

I am using a plugin that added a class open to .slide-out-div when opened.

So I am trying to change some css if the open is detected.

What I need to do is

IF  $('.slide-out-div **open**') IS Detected then  $('.otherDiv').css('top','0px'); 

Not sure how to put this together...

like image 822
Satch3000 Avatar asked Mar 07 '12 10:03

Satch3000


People also ask

How to detect class change in JavaScript?

To listen to class change we need to instantiate the MutationObserver object, pass the callback function, and call the observe() method. The observe() method accepts two arguments the target node and options object which should contain attributes property that is set to true.

How do you check if a class is added in jQuery?

jQuery hasClass() Method The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".

How to fire event if css class is changed using jQuery?

Approach: In jQuery, there is no provision to trigger an event on class change. An alternative method is to manually raise an event when you programmatically change the class using the trigger() function. The trigger() function will raise an event whenever the class of the button is changed.


2 Answers

There is no event of class-added, you will need to track it yourself...

It can be done with an infinite loop with setTimeout to check if the class has changed.

function checkForChanges() {     if ($('.slide-out-div').hasClass('open'))         $('.otherDiv').css('top','0px');     else         setTimeout(checkForChanges, 500); } 

You can call the function when you want, or onDOM ready:

$(checkForChanges); 
like image 155
gdoron is supporting Monica Avatar answered Feb 14 '23 22:02

gdoron is supporting Monica


The question's a bit old, but since I came across while looking for a similar problem, thought I'd share the solution I went with here - Mutation Observers

In your case, I'd create a mutation observer

var mut = new MutationObserver(function(mutations, mut){   // if attribute changed === 'class' && 'open' has been added, add css to 'otherDiv' }); mut.observe(document.querySelector(".slide-out-div"),{   'attributes': true }); 

The function in mutation observer is called any time an attribute of .slide-out-div is changed, so need to verify the actual change before acting.

More details here on Mozilla's documentation page

like image 40
Adi B Avatar answered Feb 14 '23 21:02

Adi B