Monitoring idle state
monitor idle state
by Seungrae Lee
HTML
<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>
CSS
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;
}
JavaScript
(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...