Resizing an element triggers the resize event of the window

Loupax picture Loupax · Apr 9, 2013 · Viewed 9.7k times · Source

Looks like that when resizing an HTML element, the windows' resize event gets fired as well.

Since I want to execute different logic when resizing elements and when the window gets resized, is there a non-hackish way of dealing with this?

http://jsfiddle.net/CPUwW/1/

$(function(){
    $(window).on('resize', function(){        
          // This event gets fired when the #my_element div gets resized, event if
          // window doesn't get resized itself
          $('#text').text(++resizes);
    });

    $('#my_element').resizable();    
});

In other words, the problem is that when I resize an element, the resize event gets fired for all of it's parents even if their size doesn't change

Answer

Daniel picture Daniel · Apr 9, 2013

Base on other information I think this one reflects the behavior of the window.

$(function () {
    var resizes = 0;

    $(window).on('resize', function () {
        $('#text').text(++resizes);
    });
    $('#my_element').resizable();

    $("#my_element").on('resize', function (e) {
        e.stopPropagation();
    });

});

http://jsfiddle.net/djwave28/CPUwW/7/

Edit: alternative and "more elegant" solution

Although the above solution works flawless, I was not satisfied with having to manage outside the resizable() widget. And it does not have to be. After digging a little deeper, it is possible to stop the propagation within the "create" phase. To show this solution I am adding it to this previous one.

$(function () {
    var resizes = 0;

    $(window).on('resize', function () {
        $('#text').text(++resizes);
    });
    $('#my_element').resizable({
        create: function (event, ui) {
            $(this).parent().on('resize', function (e) {
                e.stopPropagation();
            });
        }
    });
});

updated fiddle: http://jsfiddle.net/djwave28/CPUwW/9/