I want to automatically resize parts of my Website with the onchange-Event. But as always I got a little problem to solve. Console gives this error:
The property undefined or a null reference can not be retrieved
".
function Resize() {
var winHeight = window.innerHeight;
var winWidth = window.innerWidth;
var startElements = document.getElementsByClassName('start');
for (var i = 1; i <= startElements.length; i++) {
document.startElements[i].attachEvent('onchange', function StartResize() {
startElements[i].style.paddingLeft = winWidth * 0.1;
startElements[i].style.paddingRight = winWidth * 0.1;
});
};
};
<body onload="Resize">
Last Thing. I already wrote the script-tag in my html document at the end of the body-tag.
Remove document
from document.startElements
.
You are probably looking for Resize()
. You forgot the ()
to invoke your function.
<body onload="Resize()">
However, inline JS (like onload in your html) has never been a good practice. Check out some of these results: Why is inline JS bad?
Instead, you should attach the event listener with JavaScript like this:
window.addEventListener('load', function() {
//code here
});
Unless you want your code to only work in IE5-8, you need to use addEventListener
not attachEvent
, so that should be addEventListener('change',
I also wonder if you meant to start your loop on 1
rather than 0
. The first element will be item 0
. If you only have one item on the page, you are skipping it and starting with an item that doesn't exist.
So, also try:
for (var i = 0;