i need code like this
if($('#someElement').hasClass('test'))
{
...
}
but i need to check it persistently not in a specific position. my question is function like bind can help me or i have to use interval for checking?
i need code like this
if($('#someElement').hasClass('test'))
{
...
}
but i need to check it persistently not in a specific position. my question is function like bind can help me or i have to use interval for checking?
If you want to check like all the time. You will need to use an interval. A bind can only be used to bind events. Like click
, mouseenter
, etc.
If you want to know when an element gains a class. You should use something like:
setInterval($.proxy(function(){
if( this.hasClass("test") && !this.data("classAdded") )
{
this.data("classAdded", true);
// Class added only triggers once.
}
}, $("#el")), 50);
You can bind a custom event and then trigger whenever you change the class of your element, or you can override the addClass jQuery method calling your function inside there, doing something like that:
(function(){
// Your base, I'm in it!
var originalAddClassMethod = jQuery.fn.addClass;
jQuery.fn.addClass = function(){
// Execute the original method.
var result = originalAddClassMethod.apply( this, arguments );
// call your function
// this gets called everytime you use the addClass method
myfunction();
// return the original result
return result;
}
})();
I should advise against this last solution as bad practice, but if you want you can use it.
(the code above is taken from this answer: https://stackoverflow.com/a/1950199/580131. you can check it there.)