1

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...

Aditya Dwivedi
  • 252
  • 5
  • 20

3 Answers3

5

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);
      }
    }
Engineer S. Saad
  • 378
  • 4
  • 19
0

Subscribe to the onresize event

window.onresize = functionName
snit80
  • 623
  • 7
  • 13
0

In Internet Explorer you can use "onresize", to trigger a JavaScript function whenever size of an element(div) or body is changed.

But "onresize" does not work the same way in other browsers. Mozilla Firefox will trigger the function only when body is resized not a div.

<body onresize="myFunction()"> 

will work in every browser

<div onresize="myFunction()">

Will work only in IE

Rohith K N
  • 845
  • 6
  • 17