Aditya Dwivedi Aditya Dwivedi - 2 months ago 10
HTML Question

detect when div width is change using javascript

I am new in javascript and I want to perform some action when the div with is changed

in jquery, I use this code

var width = $(window).width();
$(window).resize(function(){
if($(this).width() != width){
width = $(this).width();
console.log(width);
}
});


but I want to do it using javascript
help me please...

Answer

You can use on-resize-event like this:

var body = document.getElementsByTagName("BODY")[0];
var width = body.offsetWidth;

if (window.addEventListener) {  // all browsers except IE before version 9
  window.addEventListener ("resize", onResizeEvent, true);
} else {
  if (window.attachEvent) {   // IE before version 9
    window.attachEvent("onresize", onResizeEvent);
  }
}

function onResizeEvent() {
  bodyElement = document.getElementsByTagName("BODY")[0];
  newWidth = bodyElement.offsetWidth;
  if(newWidth != width){
    width = newWidth;
    console.log(width);
  }
}
Comments