jeudi 30 juillet 2015

Use if statements with a number variable in JS

I am working on a gallery. So basically my idea works like this: The value of my variable picnumber is 1. If you click on the next button it will trigger my function nextpicture, and of course if you click on the previous button it will trigger my function previouspicture.

So what is the job of those functions?

  • nextpicture = picnumber + 1

  • previouspicture = picnumber + 1

Ok, so for example we have clicked on nextpicture once the value of picnumber should be 2 (if the value is 2 it should show 002.jpg)

I want to achieve that it shows a different picture on whether the value of picnumber is 1 - 6

I tried to do this with if and else if statements, however it didn't work.

var picnumber = 1;
function nextpicture(picnumber){
picnumber = picnumber + 1
}
function previouspicture(picnumber){
picnumber = picnumber - 1
}
if (picnumber == 1){
document.getElementById('gallerypicture').src = "img/gallery/001.jpg";
document.getElementById('galleryprevious').style.display = 'none';
}
else if (picnumber == 2){
document.getElementById('gallerypicture').src = "img/gallery/002.jpg";
}
else if (picnumber == 3){
document.getElementById('gallerypicture').src = "img/gallery/003.jpg";
}
else if (picnumber == 4){
document.getElementById('gallerypicture').src = "img/gallery/004.jpg";
}
else if (picnumber == 5){
document.getElementById('gallerypicture').src = "img/gallery/005.jpg";
}
else if (picnumber == 6){
document.getElementById('gallerypicture').src = "img/gallery/006.jpg";
document.getElementById('gallerynext').style.display = 'none';
}
else {  
document.getElementById('gallery').style.display = 'none';
}

Here's my HTML

<img id="gallerypicture" src="" alt="Photo">
<a href="javascript:void(0)" onclick="previouspicture(picnumber);"><div id="galleryprevious"></div></a>
<a href="javascript:void(0)" onclick="nextpicture(picnumber);"><div id="gallerynext"></div></a>

As you can see in my first and in my last if statement, I'd like to hide the div to click previous or next, so the value of picnumber can't be lower than 1 or higher than 6 (since I only have 6 pictures in this gallery)

Aucun commentaire:

Enregistrer un commentaire