Anand S Kumar
Anand S Kumar

Reputation: 90859

JavaScript: Error at document.getElementById() in Internet Explorer

I am currently facing an error in JavaScript. The code is given below

function loader() {
    size = window.innerWidth;
    size = size - 300;
    mainj = document.getElementById('main1');
    mainj.style.left = size.toString() + 'px';
    submainj = document.getElementById('submain1');
    submainj.style.left = size.toString() + 'px';
    size = mainj.style.top + 26;
    document.getElementById('submain1').style.top = size.toString() + 'px';
}
onload = loader();

The error comes only in Internet Explorer and the code works perfectly in Firefox. The error shows is in the fifth line, the error being

Message: Object required
Line: 34
Char: 1
Code: 0
URI: http://localhost/home.php

Line 34 is the 5th line given in the code - 'mainj.style.left.....' How can I fix this problem?

Upvotes: 1

Views: 1594

Answers (2)

Jordan
Jordan

Reputation: 32522

This is the offending line:

size=window.innerWidth-300;

Internet Explorer doesn't have a concept of inner width on window, as far as I know. The following code is a decent cross-browser implementation, similar to something you would see in a library. There are corresponding innerHeight and offsetHeight properties if you needed height as well.

var size = 0;
if(window.innerWidth) {
    size = window.innerWidth;
} else if (document.documentElement && document.documentElement.offsetWidth) {
    size = document.documentElement.offsetWidth;
} else if (document.body && document.body.offsetWidth) {
    size = document.body.offsetWidth;
}

Upvotes: 3

Naftali
Naftali

Reputation: 146302

Make sure you have a DOM element with ID=main1

If it does not exist then your code will return errors.

what you can do is have a conditional:

if(mainj  !== undefined) {  //if mainj is a real object
   //do code with mainj
}

Also try using local variables in your code (precede variables with the word var) so they do not enter the global scope.

Upvotes: 8

Related Questions