jQuery Window Resize

July 13th, 2011 by Cosmin Harangus Leave a reply »

For the past two months I’ve been working on a very complex web application using jQuery and Zend Framework with a strong client side orientation.

Recently I noticed a very strange bug related to the resize event of the browser window. In my app in am basically displaying events on a calendar similar to google calendar and I wanted to resize the events in case the window resizes to fit the new size of the calendar. I started writing the following code:

1
2
3
$(window).resize(function(){
    _redrawEvents();
});

Everything was going well. The _redrawEvents() function redrew the events on the page fit the new size of the window. The problem was that when I would try to resize an event using the resizable jQuery UI plugin the window resize event was triggered and the size of the calendar event would not change.

Looking over what was the target of the event in the resize handler function I realized that his handler was called for both the event divs in the calendar and the window object.
After a bit of tweaking my final code looked like this:

1
2
3
4
$(window).resize(function(event){
    if (event.target=window)
        _redrawEvents();
});

As a conclusion make sure you always check that the target of your event if correct before executing any other code.

Share

1 comment

  1. Luis Pirir says:

    Thank you for the tip !

Leave a Reply