Reputation: 568
Let's say that I have a button with fuction add a class named open
to a div#foo
element, and when it's all done I need to change other element style div#bar
fyi the default style of the div#bar
is position:fixed
So here is my code
function checkForChanges()
{
if ($('#foo').hasClass('open'))
$('#bar').css('position','relative');
else
setTimeout(checkForChanges, 500);
}
$(checkForChanges);
It woks like a charm, but the problem is how to revert the style of the #bar
to the default if #foo
no longer have class named open
?
Frankly I have no experience in javascript so I have no idea about 'setTimeout(checkForChanges, 500);`
All I need is change the #bar
style when #foo
has class open
and get the #bar
style back to the default when the #foo
no longer have class open
Upvotes: 0
Views: 609
Reputation: 2855
You shouldn't need a timeout or interval for this. Take advantage of CSS specificity:
var open = 'someCondition';
if(open) {
$('#foo').addClass('open');
$('#bar').addClass('foo-open');
} else {
$('#foo').removeClass('open');
$('#bar').removeClass('foo-open');
}
#bar {
position: fixed;
}
#bar.foo-open {
position: relative;
}
whatever code is responsible for adding the class open
to #foo
should also add a class foo-open
to #bar
.
Also have a look at cssspecificity.com for a fun visualization of CSS specificity.
Upvotes: 1
Reputation: 490
Use setInterval
instead of setTimeout
function checkForChanges()
{
if ($('#foo').hasClass('open'))
$('#bar').css('position','relative');
else
$('#bar').css('position','fixed');
}
setInterval(checkForChanges, 500);
Upvotes: 0