0

There are no errors when i do resize() into console with this code, and the the box resizes it's height to it's width.

function resize() {
    let box = document.getElementById("id");
    let width = $("#id").width();
    box.style.height = width;
}

I want to do that automatically so i just tried adding resize(); in the end of the js file like this:

function resize() {
    let box = document.getElementById("id");
    let width = $("#id").width();
    box.style.height = width;
}

resize();

But nothing happens and there is an error in the console:

Uncaught TypeError: Cannot read property 'style' of null
    at resize (main.js:4)
    at main.js:7
resize @ main.js:4
(anonymous) @ main.js:7
  • Perhaps the JavaScript executes before the [DOM is ready](https://stackoverflow.com/a/12637750/924299). – showdev Apr 25 '20 at 05:54
  • Tried wrapping the function call into a **setInterval** of 10 seconds, there was the same error in console even before the 10 seconds. –  Apr 25 '20 at 06:06
  • For more info, doing **resize()** in console works fine, but also prints **undefined**. –  Apr 25 '20 at 06:10

1 Answers1

0

You have to encapsulate your function call in a ready function, since the elements are probably not yet loaded.

$(function() {
    resize();
});
chriss
  • 320
  • 2
  • 15