1

In Pure Javascript and jQuery, How to detect if the width of an element has changed? For eg, if the width of an element changes as per css media queries when window is resized, how to detect it?

I have tried -

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

But that did not work.

I have found solutions on SO about plug-ins. Yes they work, but any pure Javascript and jquery based solution?

anand patil
  • 507
  • 1
  • 9
  • 26
  • You might like to have a look at this question http://stackoverflow.com/questions/6492683/how-to-detect-divs-dimension-changed – Redu Jun 04 '16 at 15:33
  • I also guess you can do this by instantiating a mutation observer object and initialize it with MutationObserverInit through some logical arguments, like if you like to observe attribute changes set attributes to true and even with a filter array containing the attributes that you would like to observe. https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver – Redu Jun 04 '16 at 15:57
  • As per window resize related width changes you can add an event listener for the resize event and go check your elements `offsetWidth` for instance. https://developer.mozilla.org/en-US/docs/Web/Events/resize – Redu Jun 04 '16 at 16:03

1 Answers1

0

A resize event should be applied to the window object.

You can do like this:

$(document).ready(function() {
    $(window).on('resize', '', {'width':$('.resize-watch').width()}, onResizeWatch);

});

function onResizeWatch(e)
{
    console.log('old width', e.data.width);
    console.log('new width', $('.resize-watch').width());
    $(window).off('resize');
    $(window).on('resize', '', {'width':$('.resize-watch').width()}, onResizeWatch);
}
buildok
  • 785
  • 6
  • 7