Recent Entries:

Favorite Links

onresize event and prototype

Tuesday, September 2nd, 2008

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:

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)

9 Responses to “onresize event and prototype”

  1. bobobobo Says:

    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.

  2. site admin Says:

    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.

  3. Todd Taylor Says:

    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));

  4. Maurice Says:

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

  5. Ji Says:

    Cheers. This is very helpful.

  6. Magnus Says:

    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?

  7. Darryl Says:

    Awesome tip! Thank you very much!

  8. Wing Says:

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

  9. Georges Says:

    @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

Leave a Reply