views:

114

answers:

2

I want to create my own event - OnPositionChange. Event implementation of course is not a problem. The point is, how to trigger it when top or left style has changed? Should I overwrite prototype of $.css() function, or is there a better solution?

+1  A: 

I'm not sure about an ideal method, but you could always set an interval that tracks whether those css values have changed, and then trigger the event:

//Usage same as bind
$('#element').PositionChange(function(){...});
$.fn.PositionChange = function(data, fn) {
  //Bind given function and args to event to trigger later
  var self = $(this);
  self.bind('PositionChange',data,fn);
  var top = self.offset().top;
  var left = self.offset().left;
  setInterval(function(){
    if(self.offset().top != top || self.offset().left != left){
      self.trigger('PositionChange');
      }
    top = self.offset().top;
    left = self.offset().left;
    },1000);
  //You might use a different interval than 1000 ms
  }
Lathan
A: 

I was trying diffrent thing and found best solution like this:

$.prototype.css2=$.prototype.css;
$.prototype.css=function( key, value ) {
    console.log(key);
    return this.css2(key,value);
}

With large amount of objects to check setInterval would slow down my code too much.

Thinker