Javascript simple image gallery - javascript

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

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>

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
}

Related

how do I reset img to original image after user goes idle

So far this is what I have tried. I cant seem to figure out how to reset the img src to the first image in the folder after the user does not click on a button for 5 seconds.
HTML
<div class="slider">
<div class="img-box">
<img src="images/a.jpg" class="slider-img">
</div>
<button id="first" class="btn" onclick="prev()">Prev</button>
<button id="second" class="btn" onclick="next()">Next</button>
</div>
JavaScript
var slider_img = document.querySelector('.slider-img');
var images = ['a.jpg', 'b.jpg', 'c.jpg', 'd.jpg', 'e.jpg'];
var i = 0;
function prev(){
if(i <= 0) i = images.length;
i--;
return setImg();
}
function next(){
if(i >= images.length-1) i = -1;
i++;
return setImg();
}
function setImg(){
return slider_img.setAttribute('src', "images/"+images[i]);
}
var btnDwn = document.onmousedown
function idk(){
return slider_img.setAttribute('src', "images/"+images[0]);
}
if(btnDwn == false){
setInterval(idk(),5000)
}
I'll define "inactivity/idleness" to if user stops moving mouse AND stops clicking
I do this by making a function that every time you call it, a timeout is set(and the previous timeout deleted) so that the content INSIDE the timeout ONLY activates AFTER 5 seconds of NOT BEING TRIGGERED
Do note that to be idle, stop using your mouse and do not click the functions for about 5 seconds and see it in action :D
var slider_img = document.querySelector('.slider-img');
var images = ['a.jpg', 'b.jpg', 'c.jpg', 'd.jpg', 'e.jpg'];
var i = 0; var timeout=0;
function prev(){
if(i <= 0) i = images.length;
i--; resetImg();
return setImg();
}
function next(){
if(i >= images.length-1) i = -1;
i++; resetImg();
return setImg();
}
function setImg(){
return slider_img.setAttribute('src', "images/"+images[i]);
}
function resetImg(){
clearTimeout(timeout);
timeout=setTimeout(()=>{slider_img.setAttribute('src', "images/"+images[0]);},5000);
}
//every time you click those buttons, you are 'active', now being active would also count as moving your mouse
document.body.addEventListener('mousemove',resetImg)

How to increase counter when the correct image is clicked

I have written in HTML and Javascript a webpage that cycles through an image of a lion and a frog. I have set 2 buttons to start and stop the images from cycling every 500ms. My problem is I am unsure how to go around creating a score function that counts the number of times a specific image is clicked. For example, if the frog image is clicked I want the score to +1 and if the lion image is clicked I want the score to -1.
Here is my code.
<html>
<head>
<title>Question 2</title>
<script>
var images = ["frog.jpg", "lion.jpg"] //I Created an array with both images inside
var imgInterval;
var imgi = 'empty';
var score = document.getElementById('score');
function start(){
imgInterval = setInterval(displayImage, 500); //Sets an interval for the func displayImage and for it to loop ever 500ms
}
function displayImage() {
if (imgi == 'empty') { //If the index is empty set the interval to 0 or frog.jpg
imgi = 0;
} else if (imgi == 0) { // If the index is set to 0 set it to 1 or lion.jpg
imgi = 1;
} else if (imgi == 1) { // If the idex is set to 1 set it back to 0, this creates a loop that will be run every 500ms
imgi = 0;
}
document.getElementById('image').src = images[imgi];
}
function stop(){
clearInterval(imgInterval);
}
function scoreNumb() { //This is where i think i am having issues and am unsure what to do.
if (imgi.onclick == 0) {
score + 1;
}
}
</script>
</head>
<body>
<button onclick=start()>Start Animation</button>
<button onclick=stop()>Stop Animation</button>
<br/> <br/>
<span>
<img id="image" onclick=scoreNumb() width="250px" />
</span>
<br/>
<span id="score">0</span>
</body>
</html>
replace your function scoreNumb with mine
<script>
...
var score = document.getElementById('score');
var valueScore = 0; /*created this*/
...
function scoreNumb() { //This is where i think i am having issues and am unsure what to do.
/*if (imgi.onclick == 0) {
score + 1;
}*/
/*0 = frog AND 1 = lion*/
if (imgi == 0){/*+1*/
valueScore++;
}else {
valueScore--;
}
console.log("click", valueScore);
document.getElementById('score').textContent = valueScore;
}
You are nearly there. You just need to check which image was clicked by checking the img src
If the image src is lion then you can increase the totalScore count variable update the count as well using textContent method.
function scoreNumb(e) {
if (e.getAttribute('src') == 'https://via.placeholder.com/150') {
totalScore++
} else {
totalScore--
}
score.textContent = totalScore
}
Working Demo:
var images = ["https://via.placeholder.com/150", "https://via.placeholder.com/200"] //I Created an array with both images inside
var imgInterval;
var imgi = 'empty';
var score = document.getElementById('score');
var totalScore = 0
function start() {
imgInterval = setInterval(displayImage, 1000); //Sets an interval for the func displayImage and for it to loop ever 500ms
}
function displayImage() {
if (imgi == 'empty') { //If the index is empty set the interval to 0 or frog.jpg
imgi = 0;
} else if (imgi == 0) { // If the index is set to 0 set it to 1 or lion.jpg
imgi = 1;
} else if (imgi == 1) { // If the idex is set to 1 set it back to 0, this creates a loop that will be run every 500ms
imgi = 0;
}
document.getElementById('image').src = images[imgi];
}
function stop() {
clearInterval(imgInterval);
}
function scoreNumb(e) { //This is where i think i am having issues and am unsure what to do.
if (e.getAttribute('src') == 'https://via.placeholder.com/150') {
totalScore++
} else {
totalScore--
}
score.textContent = totalScore
}
<html>
<head>
<title>Question 2</title>
<script>
</script>
</head>
<body>
<button onclick=start()>Start Animation</button>
<button onclick=stop()>Stop Animation</button>
<br /> <br />
<span>
<img id="image" onclick=scoreNumb(this) width="250px" />
</span>
<br />
<span id="score">0</span>
</body>
</html>
Change this variable declaration from:
let score = document.getElementById('score');
to this:
let score = 0;
then in the function named scoreNumb() change the following :
if (imgi.onclick == 0) {
score + 1;
}
to this :
if (imgi === 0) {
score += 1;
}
else{
score -= 1;
}
// Here you can update your html code with getElementById.
console.log(score)

How to add link only one specific page?

I would like to add a link just one page out of all the pages. I've tried some different ways, but that is not working and closing the image slide simultaneously.
var photo = ["image/pic0.jpg", "image/pic1.jpg", "image/pic2.jpg", "image/pic3.jpg", "image/pic4.jpg"];
var imgTag = document.querySelector(".slide-pic");
var count = 0;
var time = 0;
window.onload = function() {
setTimeout(next, 5000);
};
function next() {
count++;
if (count >= photo.length) {
count = 0;
imgTag.src = photo[count];
} else {
imgTag.src = photo[count];
}
}
function prev() {
count--;
if (count < 0) {
count = photo.length - 1;
imgTag.src = photo[count];
} else {
imgTag.src = photo[count];
}
}
<div class="front-pic">
<button class="left-btn" onclick="prev()"><i class="fa fa-arrow-left"></i></button>
<img id="pic-link" class="slide-pic" src="image/pic0.jpg">
<button class="right-btn" onclick="next()"><i class="fa fa-arrow-right"></i></button>
</div>
I'm not sure what exactly you were trying to achieve but I still gave it a try. Try the code snippet below and see if it works for you.
var photo = [
"https://image.shutterstock.com/image-photo/pacific-coast-highway-101-oregon-600w-1340723072.jpg",
"https://image.shutterstock.com/image-photo/cargo-train-departing-station-during-600w-1153325710.jpg",
"https://image.shutterstock.com/image-photo/california-united-states-pacific-coast-600w-322331276.jpg",
"https://image.shutterstock.com/image-photo/piha-beach-on-west-coast-600w-154908542.jpg",
"https://image.shutterstock.com/image-photo/sea-cliff-bridge-along-grand-600w-167705717.jpg"
];
var imgTag = document.querySelector(".slide-pic");
var count = 0;
var time = 0;
window.onload = function () {
setTimeout(next, 5000);
};
function next() {
count++;
if (count >= photo.length) {
count = 0;
imgTag.src = photo[count];
}
else {
imgTag.src = photo[count];
}
}
function prev() {
count--;
if (count < 0) {
count = photo.length - 1;
imgTag.src = photo[count];
}
else {
imgTag.src = photo[count];
}
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<div class="front-pic">
<button class="left-btn" onclick="prev()"><i class="fa fa-arrow-left"></i></button>
<img id="pic-link" class="slide-pic" width="200" height="200" src="https://image.shutterstock.com/image-photo/summer-landscape-blue-sky-on-600w-313318763.jpg">
<button class="right-btn" onclick="next()"><i class="fa fa-arrow-right"></i></button>
</div>
Please note the changes that I made in the original code.
I'm using / in the path of the images rather than \.
Changed the images. These are available online and were added only for the purpose of demonstration. You, of course, can give the path to your images. But, when you give a path to a static file, give a relative path instead of absolute.
I added font-awesome CDN, as I noticed you were using it for the icons in the buttons. You can change this one with the one you're currently using.

Previous button in Javascript is not working

I want to create a slider in Javascript with two buttons 'Next' and 'Previous'. The next button is working but Previous is not. Here is my code:
let myImage = document.getElementById('mainImage');
let images = ["./img/th01.jpg", "./img/th02.jpg", "./img/th03.jpg", "./img/th04.jpg", "./img/th05.jpg"];
let imageIndex = 1;
function next(){
myImage.setAttribute('src', images[imageIndex]);
imageIndex++;
if (imageIndex >= images.length) {
imageIndex = 0;
}
}
function previous(){
myImage.setAttribute('src', images[imageIndex]);
imageIndex--;
if (imageIndex <= 0) {
imageIndex = images[imageIndex];
}
}
<div id="wrapper">
<img src="./img/th01.jpg" id="mainImage">
<br>
<br>
<button onclick="previous()">Previous</button>
<button onclick="next()">Next</button>
</div>
Any help please?
Your next button isn't exactly working either. The problem in both functions is that you're changing the index after changing the src, so the new src will reflect what imageIndex was after the last button click, not the click that just occurred. (and since imageIndex is hard-coded to start at 1, the first click always looks to do what the "Next" button is supposed to do)
Initialize imageIndex to 0, and change it before setting the src.
Also, don't use inline handlers, they have a demented scope chain, require global pollution, and have quote escaping issues. Use addEventListener instead:
let myImage = document.getElementById('mainImage');
let images = ["./img/th01.jpg", "./img/th02.jpg", "./img/th03.jpg", "./img/th04.jpg", "./img/th05.jpg"];
let imageIndex = 0;
const [prev, next] = document.querySelectorAll('button');
next.addEventListener('click', () => {
imageIndex++;
if (imageIndex === images.length) {
imageIndex = 0;
}
myImage.src = images[imageIndex];
});
prev.addEventListener('click', () => {
imageIndex--;
if (imageIndex === -1) {
imageIndex = images.length - 1;
}
myImage.src = images[imageIndex];
});
<div id="wrapper">
<img src="./img/th01.jpg" id="mainImage">
<br>
<br>
<button>Previous</button>
<button>Next</button>
</div>

javascript code of an image rotator

I am trying to make an 8 image button rotator via javascript, I have buttons "<" ">" "<<" ">>" and a check box image rotator. I can send my code so far and screenshot, can someone help? here is my code.
<div id="images">
<img src="images/sample1.jpg" id="image"/>
</div>
<div id="buttonContainer">
<button id="firstImageButton" title="Click to view the first image." onClick="previousImage("image")">«</button>
<button id="previousImageButton" title="Click to view the previous image." ><</button>
<button id="nextImageButton" title="Click to view the next image." >></button>
<button id="lastImageButton" title="Click to view the last image." onClick="images/sample8.jpg">»</button>
<br/><input type="checkbox" id="autoRotate" /><label for="autoRotate">Click to auto-rotate</label>
</div>
</div>
</div>
script
<script>
var images = [ "images/sample1.jpg", "images/sample2.jpg", "images/sample3.jpg", "images/sample4.jpg", "images/sample5.jpg", "images/sample6.jpg", "images/sample7.jpg", "images/sample8.jpg" ]
var currentImageIndex = 0;
var currentImage = 0;
function nextImageButton() {
currentImage += 1;
displayImage(currentImage);
}
function previousImageButton() {
currentImage -= 1;
displayPage(currentImage);
}
function displayImage (imageIndex) {
document.getElementById("images").innerHTML = images[imageIndex];
document.getElementById("nextImageButton").style.visibility = "visible";
document.getElementById("previousImageButton").style.visibility = "visible";
if(imageIndex == images.length - 1) {
document.getElementById("nextImageButton").style.visibility = "hidden";
}
if(imageIndex == 0) {
document.getElementById("previousImageButton").style.visibility = "hidden";
}
}
</script>
change all tabs before posting.
create a jsfiddle.net with the code.
what's with the </div></div></div> ?
what is onClick="images/sample8.jpg" supposed to do?
you have the same quotes in the onclick - if you wrap quotes you need to do ="...('xxx');"
document.getElementById("images").innerHTML = images[imageIndex];
should be document.getElementById("image").src = images[imageIndex];
Live Demo
var images = [ "http://lorempixel.com/output/food-q-c-640-480-1.jpg",
"http://lorempixel.com/output/food-q-c-640-480-2.jpg",
"http://lorempixel.com/output/food-q-c-640-480-3.jpg",
"http://lorempixel.com/output/food-q-c-640-480-4.jpg",
"http://lorempixel.com/output/food-q-c-640-480-5.jpg",
"http://lorempixel.com/output/food-q-c-640-480-6.jpg",
"http://lorempixel.com/output/food-q-c-640-480-7.jpg" ]
var tId,currentImage = 0;
function changeImage(dir) {
if (dir === 0) currentImage = 0; // first image
else if (dir===images.length-1) currentImage=images.length-1; // last image
else currentImage+=dir*1; // next or previous
if (currentImage<0 || currentImage>=images.length) currentImage=0; // will wrap
displayImage(currentImage);
}
function displayImage (imageIndex) {
window.console && console.log(imageIndex); // remove when happy
// document.getElementById("msg").innerHTML=(imageIndex+1)+"/"+images.length;
document.getElementById("image").src = images[imageIndex];
document.getElementById("nextImageButton").style.visibility=(imageIndex<images.length-1)?"visible":"hidden";
document.getElementById("previousImageButton").style.visibility=(imageIndex>0)?"visible":"hidden";
}
function rotate() {
changeImage(+1);
}
window.onload=function() {
document.getElementById("autoRotate").onclick=function() {
if (this.checked) tId=setInterval(rotate,3000)
else clearInterval(tId);
}
document.getElementById("firstImageButton").onclick=function() { changeImage(0) }
document.getElementById("lastImageButton").onclick=function() { changeImage(images.length-1) }
document.getElementById("nextImageButton").onclick=function() { changeImage(1) }
document.getElementById("previousImageButton").onclick=function() { changeImage(-1) }
}

Categories

Resources