Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize on div element

jQuery has the resize() - event, but it just work with window.

jQuery(window).resize(function() { /* What ever */ }); 

This works fine! But when I want to add the event to a div element it doesn't work.

E.g.

jQuery('div').resize(function() { /* What ever */ }); 

I want to start an callback when the size of a div-element has changed. I don't want to start a resizable - event – just a event to check if the size of a div - element has changed.

Is there any solution to do this?

like image 552
TJR Avatar asked Apr 10 '12 10:04

TJR


2 Answers

DIV does not fire a resize event, so you won't be able to do exactly what you've coded, but you could look into monitoring DOM properties.

If you are actually working with something like resizables, and that is the only way for a div to change in size, then your resize plugin will probably be implementing a callback of its own.

like image 155
David Hedlund Avatar answered Sep 30 '22 19:09

David Hedlund


I was only interested for a trigger when a width of an element was changed (I don' care about height), so I created a jquery event that does exactly that, using an invisible iframe element.

$.event.special.widthChanged = {   remove: function() {       $(this).children('iframe.width-changed').remove();   },   add: function () {       var elm = $(this);       var iframe = elm.children('iframe.width-changed');       if (!iframe.length) {           iframe = $('<iframe/>').addClass('width-changed').prependTo(this);       }       var oldWidth = elm.width();       function elmResized() {           var width = elm.width();           if (oldWidth != width) {               elm.trigger('widthChanged', [width, oldWidth]);               oldWidth = width;           }       }        var timer = 0;       var ielm = iframe[0];       (ielm.contentWindow || ielm).onresize = function() {           clearTimeout(timer);           timer = setTimeout(elmResized, 20);       };   } } 

It requires the following css :

iframe.width-changed {     width: 100%;     display: block;     border: 0;     height: 0;     margin: 0; } 

You can see it in action here widthChanged fiddle

like image 20
Panos Theof Avatar answered Sep 30 '22 19:09

Panos Theof