1

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?

shayan
  • 143
  • 1
  • 5
  • 16
  • if not an interval, what would be the condition that would make the most sense to check? We have no knowledge of the other parts of your code, so its hard for us to see the connection. – thescientist Oct 13 '12 at 11:45

2 Answers2

2

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);
Niels
  • 48,601
  • 4
  • 62
  • 81
  • 1
    Ofc. it will because this code is executes every X MS. But this less of a code is not noticable by the user. But we don't know how the class is beeing added. If it's beeing added with a function you can change that jQuery function to have an extra callback. Or call a function after you have used that function. For example `addClass`. – Niels Oct 13 '12 at 11:56
  • can u tell me what is its effects? because this is javascript code and it run in client side. -interval=1s- – shayan Oct 13 '12 at 11:59
  • Currently it checks every 50MS if the `$("#el")` contained the class `test` once it has that class, a `data` property is set. And the code is executed (none code there atm) once. – Niels Oct 13 '12 at 12:20
0

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.)

Community
  • 1
  • 1
Stefano Ortisi
  • 5,288
  • 3
  • 33
  • 41