onresize event and prototype
If you need a compact way to use prototype and listen to on onresize event in a cross-browser manner, this is the way to go:
[source:js]
Event.observe(document.onresize ? document : window, "resize", function() {//dostuff});
[/source]
As you can see, the event to listen is resize but depending on the browser, it may be fired on either the window or the document object.
Quirksmode has as usual an explanation of which browser support the one or the other
Of course, you should never use the apparently simpler
[source:js]
document.onresize = function() {};
[/source]
if you want a robust solution since you will overwrite any other event listeners that can have been
add by other libraries (Bobobobo has a bad example)
[source:js]
Event.observe(document.onresize ? document : window, "resize", function() {//dostuff});
[/source]
As you can see, the event to listen is resize but depending on the browser, it may be fired on either the window or the document object.
Quirksmode has as usual an explanation of which browser support the one or the other
Of course, you should never use the apparently simpler
[source:js]
document.onresize = function() {};
[/source]
if you want a robust solution since you will overwrite any other event listeners that can have been
add by other libraries (Bobobobo has a bad example)
bad example?! ha.
ReplyDeletethere is no problem in using the shorter window.onresize syntax if you're in control of your page and you want your resize handler to be the only handler for the page.
well...your example has two problems: 1) it is not about prototype, 2) it is not browser safe since not all browsers have the document.onresize method.
ReplyDeleteHere is a way to do it using prototypes framework of binding events to the scope of a specific object/element...
ReplyDeleteEvent.observe(window, "resize", this.myfunction.bindAsEventListener(this));
Thanks mate!
ReplyDeleteI was wondering how to do it cross-browserly ^^
Cheers. This is very helpful.
ReplyDeleteAs Tod Taylor says, the prototype way to observe the resizing of the window is Event.observe(window, “resize”, this.myfunction.bindAsEventListener(this)); my problem is to stopObserving.
ReplyDeleteIt seems that one would be able to do it with Event.stopObserving, but for the window that causes the error "element.stopObserving is not a function".
In my case I use different handlers depending on the scope I'm in, whereas unbinding the event listener is needed.
Any ideas?
Awesome tip! Thank you very much!
ReplyDeleteYour example has one problem: 1) it doesn't work in Safari at all.
ReplyDelete@Magnus
ReplyDeleteThe prototype doc states that you must not use binds like that, because they create different instances of methods each time.
You have to keep reference to a a bound method instead somewhere