Reputation: 21
Im going to create simply slider in JavaScript (without jquery). I have .xhtml page with unordered list:
<ul>
<li class="slider"><img src="images/1.jpg" alt="asd" width="600px" height="400px" /></li>
<li class="slider"><img src="images/2.jpg" alt="asd" width="600px" height="400px" /></li>
<li class="slider"><img src="images/3.jpg" alt="asd" width="600px" height="400px" /></li>
<li class="slider"><img src="images/4.jpg" alt="asd" width="600px" height="400px" /></li>
<li class="slider"><img src="images/5.jpg" alt="asd" width="600px" height="400px" /></li>
<li class="slider"><img src="images/6.jpg" alt="asd" width="600px" height="400px" /></li>
<li class="slider"><img src="images/7.jpg" alt="asd" width="600px" height="400px" /></li>
</ul>
It's my script:
var s = document.getElementsByClassName('slider');
function hide()
{
for(var i = 0; i < s.length; i++)
{
s[i].style.display = "none";
}
}
var i = 0;
function sw()
{
hide();
s[i].style.display = "block";
i++;
if (i >= s.length) i = 0;
}
hide();
sw();
setInterval(sw, 1000);
Log.console show me this error: Uncaught TypeError: Cannot read property 'style' of undefined.
Upvotes: 0
Views: 64
Reputation: 32511
You're trying to grab all of your elements before they're loaded. Move your <script>
tag to the bottom of the <body>
. That way, your elements will have been loaded into the DOM.
<body>
<ul>
<li class="slider"></li>
...
</ul>
<script src="javascript/main.js"></script>
</body>
Upvotes: 1