Snake780
Snake780

Reputation: 47

slideshow sequence with one button JS

I've looked at numerous similar posts, which most of them have a previous button, but I only need one button to loop back to the original photo once it cycles through. I tried adjusting my code following along with those posts and I kind of understand but I'm still getting error after error whenever I adjust. So I wanted to make a question specific to my issue and hope that someone could explain/give guidance on where I'm going wrong.

<script>

var main = document.getElementById("tool");
var imgArray = ["/tools/saw.jpg","/tools/chisels.jpg","/tools/pitchfork.jpg"];
var imgIndex = 0;

function switchImg(){
    main.setAttribute("src",imgArray[imgIndex]);
    imgIndex = (imgIndex +1) % imgArray.length;
    }


</script>

<style>
img{
display: block;
margin-left: auto;
margin-right: auto;
}
.buttons{
text-align: center;
}
</style>
</head>
<body>

<img id="tool" src="/tools/saw.jpg"  height="248" width="364" alt="Saw"/>


<br/>

<div class="buttons">
<button type="button"  onClick="switchImg();"> Next </button>

Error

enter image description here

I thought I might need a for statement, but I dont understand how I would call the id=tool (inside the body) into the for statement. Any help is greatly appreciated.

Upvotes: 0

Views: 29

Answers (1)

Odinn
Odinn

Reputation: 1106

Your html element doesn't exist yet. You need to put your script at the bottom

Like this:

<style>
img{
display: block;
margin-left: auto;
margin-right: auto;
}
.buttons{
text-align: center;
}
</style>
</head>
<body>

<img id="tool" src="/tools/saw.jpg"  height="248" width="364" alt="Saw"/>


<br/>

<div class="buttons">
<button type="button"  onClick="switchImg();"> Next </button>
    <script>

var main = document.getElementById("tool");
var imgArray = ["/tools/saw.jpg","/tools/chisels.jpg","/tools/pitchfork.jpg"];
var imgIndex = 0;

function switchImg(){
    main.setAttribute("src",imgArray[imgIndex]);
    imgIndex = (imgIndex +1) % imgArray.length;
    }


</script>

Because of loading HTML it load from the top to bottom, header is first then body and everything inside the body. That's why best practice is to put your tag at the bottom before the closing tag

Also you can use

window.onload

or jQuery

$( document ).ready()

Upvotes: 1

Related Questions