0

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.

Aditya
  • 2,876
  • 4
  • 34
  • 30
Armin Bu
  • 1,330
  • 9
  • 17

1 Answers1

1

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;
m59
  • 43,214
  • 14
  • 119
  • 136
  • Thank you for the advise! I just forgot to invoke it in my question in my code i did, sry for the mistake. But what i am really looking for is a mistake with the .getElementsByClassName(''). I think it doesnt work with the Eventlistener – Armin Bu Jan 26 '14 at 15:30
  • @user3237742 one more update I added - you probably meant to start your loop with `i=0` not `i=1`. I updated my answer again. – m59 Jan 26 '14 at 15:40
  • Oh i solved it by myself :D i wrote document.startElements[i].addEventListener(... but it should be like this: startElements[i].addEventListener(... – Armin Bu Jan 26 '14 at 15:49