GusDeCooL GusDeCooL -4 years ago 105
Javascript Question

jQuery(event): watch element style

let say have element like this

<div class="watch-me" style="display: none;">Watch Me Please</div>

as we can see the element above style is
display: none
, how can i make script to watch this element. when that element style is change to
display: block
then there is some code will be trigger.

many thanks...

Answer Source

As far as I know, the only way to do this would be with a timer.

I created a small jQuery plugin (yes, right here, right now) that does this against a jQuery set:

EDIT this plugin is now on GitHub:

$ = function(property, callback) {
   return $(this).each(function() {
       var self = this;
       var old_property_val = this[property];
       var timer;

       function watch() {
          if($(self).data(property + '-watch-abort') == true) {
             timer = clearInterval(timer);
             $(self).data(property + '-watch-abort', null);

          if(self[property] != old_property_val) {
             old_property_val = self[property];
       timer = setInterval(watch, 700);

$.fn.unwatch = function(property) {
   return $(this).each(function() {
       $(this).data(property + '-watch-abort', true);


$('.watch-me').watch('style', function() {
   //"this" in this scope will reference the object on which the property changed
   if($(this).css('display') == 'block') { 
       //do something...

To clear this property watcher:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download