Tuesday, 2 September 2008

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)

9 comments:

  1. 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.

    ReplyDelete
  2. 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.

    ReplyDelete
  3. 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));

    ReplyDelete
  4. Thanks mate!
    I was wondering how to do it cross-browserly ^^

    ReplyDelete
  5. Cheers. This is very helpful.

    ReplyDelete
  6. 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?

    ReplyDelete
  7. Awesome tip! Thank you very much!

    ReplyDelete
  8. Your example has one problem: 1) it doesn't work in Safari at all.

    ReplyDelete
  9. @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

    ReplyDelete