onresize event and prototype
Tuesday, September 2nd, 2008If 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:
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
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)
Tags: Javascript, listener, onresize, prototype, resize event, window|
Posted in Javascript, Programming
September 2nd, 2008 at 11:42 pm
bad example?! ha.
there 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.
September 3rd, 2008 at 7:54 am
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.
October 27th, 2008 at 3:20 am
Here is a way to do it using prototypes framework of binding events to the scope of a specific object/element…
Event.observe(window, “resize”, this.myfunction.bindAsEventListener(this));
May 21st, 2009 at 2:25 pm
Thanks mate!
I was wondering how to do it cross-browserly ^^
September 10th, 2009 at 12:09 pm
Cheers. This is very helpful.
December 2nd, 2009 at 10:35 am
As 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.
It 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?
February 25th, 2010 at 10:44 am
Awesome tip! Thank you very much!
March 27th, 2010 at 6:29 am
Your example has one problem: 1) it doesn’t work in Safari at all.
June 11th, 2010 at 3:27 am
@Magnus
The 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