Sunday, August 05, 2007

prototype javascript library Element event observe example


<a href="http://www.baidu.com" id="a1"> baidu </a>
<script type="text/javascript" charset="utf-8">
/*Event.observe('a1', 'click', function (o) {
alert(o.eventPhase + o.type);
//Event.stop(o);
}, false);

Event.observe('a1', 'click', function (o) {
alert(o.eventPhase);
Event.stop(o);
}, true);*/

/*Object.extend(Element.prototype, {
click: function (callback) {
this.onclick = callback;
},
mouseout: function (callback) {
this.onmouseout = function (evt) {
alert(evt.eventPhase);
callback.apply(this, $A(arguments));
}
}
});*/

var evts = ("blur,focus,load,resize,scroll,unload,click,dblclick," +
"mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
"submit,keydown,keypress,keyup,error
").split(",");
evts.each(function (e) {
Element.prototype[e] = function (handler) {
this['on' + e] = handler;
}
});
var a1 = $('a1');
a1.click(function (e) {
alert(e.type);
Event.stop(e);
});
a1.click(function (e) {
alert(e.eventPhase);
Event.stop(e);
}); // will override before a1.click handler
a1.mouseout(function (e) {
alert(e.type);
});
</script>

event observe o.eventPhase #=> 2
Event.stop will prevent event performed, browser will not go to baidu.com

No comments :