(function($) {
$.extend($.fn, {
monitor: function(options) {
return this.each(function () {
$.creator(this, options);
});
}
});
// instance creator
$.creator = function(target, options) {
// check if a monitor was already created
if (target.monitor) {
target.monitor.init();
} else {
target.monitor = new $.monitor(options, target);
} //if~else
return target.monitor;
};
// constructor for monitor
$.monitor = function(options, target) {
this.o = $.extend(true, {}, $.monitor.defaults, options);
this.target = target;
this.init();
};
$.extend($.monitor, {
defaults: {
timeout: 500,
events: [scroll]
},
setDefaults: function(settings) {
$.extend($.monitor.defaults, settings);
},
prototype: {
init: function() {
this._idleTime = null;
this._timer = null;
this._state = "on";
this.idleTime = null;
// add event listener
this.initObservers(this.target, this.o.events);
this.setTimer(this.target);
},
initObservers: function(target, events) {
var self = this;
$.each(events, function(i, e) {
$(target).bind(e, function(event) {
self.onInterrupt(target, event);
});
});
},
onInterrupt: function(target, event) {
this.idleTime = new Date() - this._idleTime;
$(target).bind("state:active", function() {}).trigger("state:active", $.monitor.onActive(this.idleTime));
this.setTimer(target);
},
setTimer: function(target) {
clearTimeout(this._timer);
if (this._state == "on") {
this._idleTime = new Date();
this._timer = setTimeout(function() {
$(target).bind("state:idle", function() {}).trigger("state:idle", $.monitor.onIdle());
}, this.o.timeout);
}
}
},
onMonitor: function() {
this._state = "off";
},
offMonitor: function() {
this._state = "on";
},
onIdle: function() {
return false;
},
onActive: function(args) {
return false;
}
});
})(jQuery);
function debug(txt) {
$("#debug").text(txt);
}
//override default onActive method
$.monitor.onActive = function(args) {
$("p").css("opacity", 1);
debug("active... after: " + args + "ms");
};
//override default onIdle method
$.monitor.onIdle = function() {
$("p").css("opacity", 0.2);
debug("idle...");
};
$(function() {
/*$(document).monitor({
timeout: 5000,
events: ['mousemove', 'keydown']
});
$(window).monitor({
events: ['resize', 'scroll']
});*/
$("input, select").monitor({
events: ['change']
});
});
<div id="bd-wrapper">
<p style="opacity:0.2">You can observe object's idle state. The object you can observe are windows, document, div and etc. The default timeout between observation is 200ms.</p>date:
<input type="text" name="field1" size="15" value="1" />
<br>
<label for="field2">select the favorite fruit:</label>
<select name="field2">
<option value="">--</option>
<option value="1">banana</option>
<option value="2">apple</option>
<option value="3">kakao</option>
<option value="4">pear</option>
</select>
<div id="debug">let's see...</div>
</div>
body {
background: #555;
}
#bd-wrapper {
width: 720px;
margin: 1em auto;
background: #333;
color: #fdd;
padding: 1em;
}
p {
color: #aaf;
font: 1em/1.5 Georgia, serif;
}
a {
color: #aaf;
}