This is a image slider. Basically taken from w3school.
<head>
<script src="code.js"></script>
</head>
<body>
<section id="slider">
<img class="sliderImage" src="images/slider/1.jpg" style="width:100%">
<img class="sliderImage" src="images/slider/2.jpg" style="width:100%">
<img class="sliderImage" src="images/slider/3.jpg" style="width:100%">
<img class="sliderImage" src="images/slider/4.jpg" style="width:100%">
<a id="sliderprev" onclick="plusDivs(-1)"> ❮ </a>
<a id="slidernext" onclick="plusDivs(1)"> ❯ </a>
</section>
</body>
And the external js file:
var slideIndex=1;
sliderFunction(slideIndex);
function plusDivs(a){
sliderFunction(slideIndex += a);
}
function sliderFunction(a){
var i;
var b = document.getElementsByClassName("sliderImage");
if(a > b.length){
slideIndex = 1;
}
if(a < 1){
slideIndex = b.length;
}
for(i=0; i < b.length; i++){
b[i].style.display = "none";
}
b[slideIndex-1].style.display = "block";
}
So it only works whenever I place <script> after those <image> and <a>. I know this that js file loads before document and that's causing the problem. How exactly do I solve this?
<head>because it will block the page loading until the JS file is 100% loaded. Put it at the end of the<body>instead.