简体   繁体   中英

How to fire event on general DOM object resize with jquery

There is an event on window resize.

$(window).resize(function() {
    ...
});

But what would it be if I want to fire the event on any type if DOM objects, like:

$('div#myDiv').resize(function() {
    ...
));

But the above seemed not work. Is this possible and convenient? Or any other good way?

This isn't possible - but shouldn't really be necessary either. If your div is changing size based on the window size, ie via a media query, just use $(window).resize(). If it's changing via some other javascript code, you should just hook into that code.

If you wanted to, you could trigger a resize event on the div and listen to that, but you'd still be triggering the event manually - ie

$('div#myDiv').on('custom_resize', function() {
    ...
));

// whenever you change div size
$('div#myDiv').trigger('custom_resize');

If you don't have any access to the code changing the div, you could poll for changes in width/height - for example (just for width):

var div_width = $('div#myDiv').width();
setInterval(function() {
    if (div_width != $('div#myDiv').width()) {
        div_width = $('div#myDiv').width();
        $('div#myDiv').trigger('custom_resize');
    }
}, 1);

If you're adding an image dynamically, this should work:

$('<img>').on('load', function() { ... })
          .attr('src', {img url})
          .appendTo({container})

This plugin offers the ability to create resize events based on an element:

A Cross-Browser, Event-based, Element Resize Detection.

In short, this implementation does NOT use an internal timer to detect size changes (as most implementations I found do). It uses scroll events on most browsers, and the onresize event on IE10 and below.

The method used not only detects javascript generated resize changes but also changes made from CSS pseudo classes eg :hover, CSS animations, etc.

https://github.com/sdecima/javascript-detect-element-resize

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM