Reputation: 29
im trying to make a simple javascript photo gallery, in which u can change the img by 2 buttons, to the previous one and to the next one, there are 9 images and if the 9th image is shown and u press next, it should show the first one img, could anyone help me please? My code doesnt work.
HTML:
<body>
<img src="img (1).jpg" alt="" height="200">
<button id="previous">previous image</button>
<button id="next">next image</button>
JS:
<script>
let counter = 1;
let img = document.querySelector("img");
let changeImg = function (type) {
if (type == 1) {
counter++
} else {
counter--
}
if (counter <= 0) {
counter = 9
}
img.setAttribute("src", "img ("+counter+").jpeg")
}
let previous = document.getElementById("previous")
let next = document.getElementById("next")
previous.addEventListener("click", chaneImg(1))
next.addEventListener("click", changeImg(2))
thanks
Upvotes: 2
Views: 386
Reputation: 11042
Not tested, but a couple of things I see are:
typo on this line:
previous.addEventListener("click", changeImg(1))
chaneImg(1)
to changeImg(1)
You also don't have a condition to check the inverse of this:
if (counter <= 0) {
counter = 9
}
so try adding
if (counter >= 9) {
counter = 1
}
Upvotes: 2
Reputation: 3856
Your problem is with the way you have added your listeners:
previous.addEventListener("click", changeImg(1))
should be
previous.addEventListener("click", (e) => changeImg(1))
The first one calls changeImage on load.
let counter = 1;
let img = document.querySelector("img");
let changeImg = function(type) {
if (type == 1) {
counter++
} else {
counter--
}
if (counter <= 0) {
counter = 9
}
img.setAttribute("src", "img (" + counter + ").jpeg")
}
let previous = document.getElementById("previous")
let next = document.getElementById("next")
previous.addEventListener("click", (_e) => changeImg(1))
next.addEventListener("click", (_e) => changeImg(2))
<body>
<img src="https://i.imgur.com/Att5gPe.jpg" alt="" height="200">
<button id="previous">previous image</button>
<button id="next">next image</button>
</body>
Upvotes: 4