Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting properties on jQuery elements

is it OK to temporarily set properties on jQuery elements to let other function know that something is happening to that element?

For example:

  • a function is doing animations with a element
  • the user clicks on something that triggers another function that will animate the same element

=> one of the animations will fail and screw up the css :(

So maybe it's better to set a property on that element, like el.animating = true while animations are running; this way other functions know what's happening and stop...

like image 787
Alex Avatar asked Jul 23 '26 23:07

Alex


2 Answers

You can use the animated-selector[docs] to test if the element is currently being animated before running your animations:

if( !$(this).is(':animated') ) {

    $(this).animate({/*...*/});

}

Example: http://jsfiddle.net/AGmX8/

like image 135
user113716 Avatar answered Jul 26 '26 12:07

user113716


I think you have two possibilities:

  1. Use classes as flags. See addClass [docs], removeClass [docs], hasClass [docs].
  2. Use .data() [docs] to associate arbitrary data with elements.

You could set properties on jQuery objects, but this only works if you keep a reference to this specific instance. Every time you pass a selector to $(), you get a new jQuery object. Thus something like:

$('div').foo = "bar";
alert($('div').foo);

does not work.

like image 41
Felix Kling Avatar answered Jul 26 '26 12:07

Felix Kling