Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resizing an element triggers the resize event of the window

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

like image 454
Loupax Avatar asked Apr 09 '13 13:04

Loupax


3 Answers

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/

like image 196
Daniel Avatar answered Nov 15 '22 06:11

Daniel


Use e.target:

SEE DEMO

$(window).on('resize', function(e){
        if(e.target===this)        
           $('#text').text(++resizes);
    });
like image 37
A. Wolff Avatar answered Nov 15 '22 07:11

A. Wolff


Works for me Demo

    if (e.originalEvent.type == 'resize'){
        $('#textWindow').text(++resizesWindow);
    } else {
        $('#text').text(++resizes);
    }
like image 24
b0zar Avatar answered Nov 15 '22 07:11

b0zar