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

4
  • stackoverflow.com/questions/15205609/… Commented Oct 4, 2016 at 6:35
  • Why would you not want to do this with jQuery? Commented Oct 4, 2016 at 6:40
  • 2
    actually, I don't want to use jquery on my whole site because I have not included jquery on my site it take 91 kb and I am, try reduce the size of my website Commented Oct 4, 2016 at 6:47
  • Use ResizeObserver: stackoverflow.com/a/39312522/47528 Commented May 4, 2020 at 13:33

3 Answers 3

6

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);
      }
    }

Sign up to request clarification or add additional context in comments.

Comments

0

Subscribe to the onresize event

window.onresize = functionName

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.