Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
28
rated 0 times [  35] [ 7]  / answers: 1 / hits: 15751  / 10 Years ago, tue, june 17, 2014, 12:00:00

I have been working on a small aspect of my application today and wanted to get a sliding bar on my application. I asked a question this morning where there was some good answers. I have recently wanted to try and answer that i ws given using Script, CSS and HTML.



I am getting to problem to get the Script working as it keeps coming up with an error saying:



 0x800a138f - JavaScript runtime error: Unable to get property 'addEventListener' of undefined or null reference


This is the Script:



<script type=text/javascript>

var desktops = document.querySelectorAll('.desktop');

function hide(element) {
element.style.setProperty('left', '-100%', element.style.getPropertyPriority('left'));
}

function hideAll() {
for (var i = 0; i < desktops.length; i++) {
hide(desktops[i]);
}
}

function show(element) {
element.style.setProperty('left', '0', element.style.getPropertyPriority('left'));
}

document.getElementById('link-one').addEventListener('click', function () {
hideAll();
show(document.getElementById('one'));
}, false);


show(document.getElementById('one'));
</script>


Here is the HTML:



<ul>
<li id=link-one>
<div>1</div>
<div>One</div>
</li>
</ul>

<div id=one class=desktop>
<h1>Sidebar Example</h1>
<p>This is 1</p>
<p>Something here.</p>
</div>


From what I can work out its not being able to find the ID?


More From » html

 Answers
39

The problem is that you're running the script BEFORE the elements on the page have been created. That is why the getElementById is returning null.



There are several ways to get around this...




  • (as commented by Kendall) you can move the script to the end of the <body>

  • You can put your code in a function, and call that function from <body onload=newFunction();>

  • If you can use jQuery, you can wrap the code in $(function() { ... });


[#70538] Sunday, June 15, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aman

Total Points: 341
Total Questions: 92
Total Answers: 92

Location: Papua New Guinea
Member since Thu, Jul 9, 2020
4 Years ago
;