Previous button in Javascript is not working - javascript

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>

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)

Javascript simple image gallery

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
}

my script js does not change my photo src

I would like to add images dynamically and have the image slider. I wrote some script, and in console I see changing src, but in HTML tere is still one picture.
Here is a code:
HTML:
<div class="sliderItau">
<a class="prevButton"> <img alt="prevButton" src="/images/prev.png"></a>
<div class="jcarousel">
<img id="image" src="/images/debito/itau_tela_02.png" alt=""></div>
<a class="nextButton"><img alt="nextButton" src="/images/next.png"></a>
</div>
JS:
const images = []
let slideIndex = 1
function preload_images() {
var image = new Image()
image.src = 'images/debito/itau_tela_01.png'
images[0] = image
image = new Image()
image.src = 'images/debito/itau_tela_02.png'
images[1] = image
image = new Image()
image.src = 'images/debito/itau_tela_03.png'
images[2] = image
}
preload_images()
const showSlidesItau = function (n) {
let img = document.getElementById('image')
let slides = img.src
slides = images[slideIndex].src
console.log(slides)
console.log(images[slideIndex].src)
if (n > slides.length) {
slideIndex = 1
}
if (n < 1) {
slideIndex = slides.length
}
}
const plusSlides = function (n) {
console.log(slideIndex)
showSlidesItau((slideIndex += n))
}
const next = document.querySelector('.nextButton')
const prev = document.querySelector('.prevButton')
//buttons ITAU
next.addEventListener('click', function () {
plusSlides(+1)
})
prev.addEventListener('click', function () {
plusSlides(-1)
})
So every time I press the button prev or next my src in colse has change. But not in HTML. Any idea why?
I am not a JS-Pro, but I wanted to point out a few things.
As GuyIncognito already wrote in the comments, you have to set the src-attribute directly, not on a copied variable. But there are some more flaws in your showSlidesItau() function:
Do your checks before setting the image source - not after
If n or slideIndex is out of the index range of your image array, you will still try to set it and receive an error.
Set your slideIndex to n
Otherwise the only times the image will change, is when the you are at the beginning or end of your image array...
Array indices start at 0 and end at array.length -1
So if you try something like array[array.length] you will receive an error.
I tried to rewrite the function a little bit:
const showSlidesItau = function (n) {
let img = document.getElementById("image");
// First check the index
if (n >= images.length) {
slideIndex = 0;
} else if (n < 0) {
slideIndex = images.length - 1;
} else {
slideIndex = n;
}
// then set the src attribute
img.src = images[slideIndex].src;
console.log(images[slideIndex].src);
};
I hope I could help you a bit.

In javascript, I not success to stop my loop with clearIntereval for setInterval

I have a countdown who will display a new piture every 5 secondes >> it approximatively work, but at the end of the array composed by 10 pictures, I am not able to stop countdown + stop to display picture with the clearInterval...
My script
<script>
var myImage = document.getElementById ("mainImage");
var imageArray = ["img/lunge.png",
"img/plank.png",
"img/push-up-and-rotation.png",
"img/push-up.png",
"img/side-plank-left.png",
"img/side-plank-right.png",
"img/squat.png",
"img/step-up-onto-chair.png",
"img/triceps-dip-on-chair.png",
"img/wall-sit.png"]
var imageIndex = 0;
$(document).ready(function () {
$('#submit').click(function () {
$('.timer').circularCountDown()
var inter = setInterval (changeImage, 5000);
function changeImage () {
myImage.setAttribute ("src", imageArray [imageIndex]);
document.getElementById("circle").innerHTML = "";
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex =0;
}
$('.timer').circularCountDown()
}
function stopinter () {
clearInterval (inter);
}
})
})
</script>
Any idea about how to do of improve my script ?
Thank you,
Olivier
imageIndex++;
if (imageIndex >= imageArray.length) {
stopinter();
}
Finaly, I make it work with this solution :
$('.timer').circularCountDown()
for (;i==10;i++) {
clearInterval (inter);
}

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