slolife slolife - 2 months ago 9x
jQuery Question

How to know when an DOM element moves or is resized

I'd like to know if there is a DOM event to listen for that tells me when a DOM element moves is repositioned or is resized on the page. I am not talking about an elements being drag/dropped. An example is if a have a list of three items on a page, and I use JS to remove one of the top two list items from the page (or hide it or whatever), I'd like to attach a handler to run when the third list item gets moved up in the page.

I am using jQuery, so plain javascript or jQuery answers are acceptable.

Maybe there are no move/position/resize events at the element level, so if there is a page/doc level event that will tell me that the page was repainted and I can check if I need to call a function again?


I put a transparent div over an element while a webservice call is made to delete that element. Since I need to absolutely position that overlay div, I want it to track the element that it covers initially. In effect anchoring it to the base element.


You can't get a callback for element movement/resizing in general; you would have to keep constantly checking the dimensions in an interval poller, which would make it a bit less responsive. You could improve this by calling the checker on a window resize event too (and scroll if overflow or fixed positioning is involved. You could also add DOM Mutation Event listeners to get informed when elements are removed from the document tree, but this doesn't work in all browsers.

Can't you do an overlay with plain CSS? eg. put position: relative on the element to be obscured, then add the overlay inside it, with the followin?

position: absolute;
z-index: 10;
left: 0;
top: 0;
width: 100%;
height: 100%;
opacity: 0.5;