Javascript slideshow shows no image for one iteration - javascript

The slideshow shows pic1.jpg through pic8.jpg and then no image for 4 seconds and then starts back at pic1.jpg. I want it to go right back to pic1.jpg after pic8.jpg.
Here is my script:
<script>
var pics = ["pic1.jpg", "pic2.jpg", "pic3.jpg", "pic4.jpg", "pic5.jpg", "pic6.jpg", "pic7.jpg", "pic8.jpg"];
var i = 1;
function changeImage() {
var image = document.getElementById('homeslideshow');
if (i < pics.length) {
image.src = pics[i]
i++;
}
else {
image.src = pics[i]
i = 0;
}
}
</script>
The function is called in the html with:
<body onload="setInterval(function(){changeImage()}, 4000)">
And the slideshow is displayed with:
<div id="section">
<img id="homeslideshow" src="pic1.jpg" alt="goofy" width="100%" height=auto>
</div>
I am a total newbie to html/css/js, so please be nice! Any help would be much appreciated.

Replace your else block as below
else {
i = 0;
image.src = pics[i];
}
as in your code, when you was setting the image.src before setting the value of i to 0, actually you were setting the image src with pics[8] which was not valid.
Also, you are missing a ; after image.src = pics[i] in the if block.
UPDATE
Replace your JS as below to solve your 8 seconds problem
<script>
var pics = ["pic1.jpg", "pic2.jpg", "pic3.jpg", "pic4.jpg", "pic5.jpg", "pic6.jpg", "pic7.jpg", "pic8.jpg"];
var i = 0;
function changeImage() {
var image = document.getElementById('homeslideshow');
if (i < pics.length-1) {
i++;
image.src = pics[i];
}
else {
i = 0;
image.src = pics[i];
}
}
</script>

You use 4000ms delay. Remove that.
setInterval(function(){changeImage()})

Related

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.

How can I make the slideshow stop? And what ways can I improve the code?

I have a slideshow that (for testing purposes) swipes through every 1 second. I have it to stop when it gets back to the first image. But when it stops on it and I click on the next button nothing happens. And when I do mess with it it will start swiping through again.
I've tried while statements but that's really it.
My code:
var i = 0;
var images = [];
var time = 1000;
images[0] = 'michael-baird-14942-unsplash.jpg';
images[1] = 'kees-streefkerk-352781-unsplash.jpg';
images[2] = 'hakon-sataoen-1484216-unsplash.jpg';
images[3] = 'mario-silva-1492028-unsplash.jpg';
images[4] = 'will-turner-1474611-unsplash.jpg';
function changeImg() {
document.slide.src = images[i];
if (i < images.length) {
i++;
} else if (i > 4) {
document.slide.src = images[0];
} else {
i = 0;
}
if (i == 0) {
$('.next').on('click', function() {
i++;
});
}
setTimeout("changeImg()", time);
}
window.onload = changeImg;
.slideshow {
width: 100%;
height: 75%;
position: absolute;
top: 42px;
}
.slideshow img {
object-fit: cover;
width: 100%;
height: 100%;
}
<div class="slideshow">
<img name="slide" alt="Slideshow Images" width="100%" height="100%">
<a class="next">❯</a>
<a class="prev">❮</a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="masterjs.js" charset="utf-8"></script>
As you can see in the JavaScript it goes through and stops at the first image. But as you can also see that this isn't a very good way to do this. If you guys can can you try to keep it in JavaScript/jQuery? If not or there is a better way please post it. But basically because of the way that it is it cycles through stops at the beginning and stays but if you mess with it VIA the next button it causes it to restart. I basically want it to cycle through the images and then stop at the beginning allowing the user to then cycle through them themselves. Also I want to add animations between images that's why I am asking for other ways that may be better for that too.
The issue is with this condition:
else if (i > 4) {
document.slide.src = images[0];
}
Your image updates to the first element of the images array, and your counter stops incrementing. Try mentally running through your code while keeping track of the value of i. Once this condition is met, does it ever stop being met?
The solution is simple, just reset the value of i when you reset the image:
else if (i > 4) {
document.slide.src = images[0];
i = 0;
}
You may then run into issues with your event listener as it triggers when i == 0, and therefore will be triggered when i is reset as above. There are some good reasons to use i === 0 instead, I recommend looking into it!
In addition, you should consider using a array.push() to add to the images array.
Finally I'd also recommend using console.log() as a way to keep track of what your code is actually doing -- this should aid in the debugging process.
Refer Below javascript code
<script type="text/javascript">
var i = 0;
var firstSlide = 0;
var images = [];
var time = 1000;
images[0] = 'https://i.ytimg.com/vi/SiVr9DM_EG0/maxresdefault.jpg';
images[1] = 'https://upload.wikimedia.org/wikipedia/en/d/d4/Mickey_Mouse.png';
images[2] = 'https://files.brightside.me/files/news/part_41/419860/18057510-1549810-23-0-1513767199-1513767212-650-1-1513767212-650-ce9f862cd3-1513864405.jpg';
images[3] = 'http://ichef.bbci.co.uk/news/999/mcs/media/images/80286000/png/_80286528_penisvagina.png';
images[4] = 'https://d345cba086ha3o.cloudfront.net/wp-content/uploads/2015/12/Chota-Bheem-Aur-Krishna-Drawing-e1451484119715.jpg';
function changeImg() {
if (i <= images.length && firstSlide == 0) {
document.slide.src = images[i];
if (i < images.length) {
i++;
} else if (i > 4) {
document.slide.src = images[0];
} else {
i = 0;
}
setTimeout("changeImg()", time);
}
}
$('.next').on('click', function() {
firstSlide = 1;
i++;
var ind = (i % 5);
document.slide.src = images[ind];
});
$('.prev').on('click', function() {
firstSlide = 1;
i--;
var ind = (i % 5);
document.slide.src = images[ind];
});
window.onload = changeImg;
</script>

JavaScript Image Gallery 2

I don't know if this question has been asked before or not. But...
I have the following JavaScript code in my HTML file:
<img id="imageDisplay">
<script type="text/javascript">
var displayImage = document.querySelector( '#imageDisplay' );
var imageArray = [ 'http://www.joongcho.com/Images/30th-Bday-Party-01.jpg',
'http://www.joongcho.com/Images/30th-Bday-Party-02.jpg',
'http://www.joongcho.com/Images/30th-Bday-Party-03.jpg',
'http://www.joongcho.com/Images/30th-Bday-Party-04.jpg',
'http://www.joongcho.com/Images/30th-Bday-Party-05.jpg',
'http://www.joongcho.com/Images/30th-Bday-Party-06.jpg' ];
var imageCount = 0;
var imageLength = imageArray.length;
displayImage.setAttribute( 'src', imageArray[ imageCount ] );
function nextImage(imageCount) {
}
function previousImage(imageCount) {
}
</script>
I'm trying to put a next Image and a previous Image function for this HTML.
For the next image, if there are more than 1 images and the image is not the last image, then there should be a link that allows a user to click through the array forwards. Also, if the image is the last image in the array, then the link is hidden.
For the previous image, if the image is not the first image of the array, then there should be a link that allows a user click through the array backwards. if the image is the first image, then the previous link should be hidden.
Any help is appreciated.
You have to attach event listeners to buttons or links (I used buttons):
var displayImage = document.getElementById('imageDisplay');
var buttonPrev = document.getElementById('button-prev');
var buttonNext = document.getElementById('button-next');
var imageArray = [ '../Images/30th-Bday-Party-01.jpg',
'../Images/30th-Bday-Party-02.jpg',
'../Images/30th-Bday-Party-03.jpg',
'../Images/30th-Bday-Party-04.jpg',
'../Images/30th-Bday-Party-05.jpg',
'../Images/30th-Bday-Party-06.jpg' ];
var imageCount = 0;
var imageLength = imageArray.length;
function nextImage () {
imageCount++;
if (imageCount >= imageLength - 1) {
buttonNext.style.display = 'none';
imageCount = imageLength - 1;
}
if (imageCount < imageLength) {
displayImage.setAttribute('src', imageArray[imageCount]);
}
if (imageCount > 0) {
buttonPrev.style.display = 'inline';
}
}
function previousImage () {
imageCount--;
if (imageCount <= 0) {
buttonPrev.style.display = 'none';
imageCount = 0;
}
if (imageCount >= 0) {
displayImage.setAttribute('src', imageArray[imageCount]);
}
if (imageCount < imageLength) {
buttonNext.style.display = 'inline';
}
}
displayImage.setAttribute('src', imageArray[imageCount]);
displayImage.textContent = imageCount;
buttonPrev.style.display = 'none';
buttonNext.addEventListener('click', nextImage);
buttonPrev.addEventListener('click', previousImage);
<img id="imageDisplay" />
<button id="button-prev">Back</button>
<button id="button-next">Forward</button>
Of course, you can't look at the images yet.

Javascript changing an image within a div after a certain amount of time

I am currently making a web page with an image inside of a div tag. I wrote a script to change the image after a certain amount of time, and it works fine when I test the script alone, however; when I attempt to place the script within my web page, it does not change the image.
Here is the code for my script:
<!DOCTYPE html>
<html>
<body>
<script>
images = new Array;
images[0] = "img2.gif";
images[1] = "img3.gif";
images[2] = "img4.gif";
images[3] = "img5.gif";
images[4] = "img6.gif";
images[5] = "img7.gif";
images[6] = "img8.gif";
images[7] = "img9.gif";
images[8] = "img10.gif";
setInterval( function() {
changeImage()
}, 5000);
x = 0;
function changeImage() {
document.getElementById('ad').src = images[x];
if ( x < 8 ) {
x += 1;
} else if ( x = 9 ) {
x = 0;
}
}
</script>
<img id='ad' src="img.gif">
</body>
</html>
I have tested this script with the image inside of a div tag and it still works fine. When I put the same code into my web page, it does not work. Also note, the image file names are just examples. The images I am using are from photobucket, so I have very little control over what they are called. Any help I could get on this would be greatly appreciated.
You need to put your code inside window.onload = function() {}
var images = new Array();
images[0] = "img2.gif";
images[1] = "img3.gif";
images[2] = "img4.gif";
images[3] = "img5.gif";
images[4] = "img6.gif";
images[5] = "img7.gif";
images[6] = "img8.gif";
images[7] = "img9.gif";
images[8] = "img10.gif";
function changeImage() {
document.getElementById('ad').src = images[x];
if (x<8) {
x+=1;
}
else if (x===9) {
x=0;
}
}
window.onload = function() {
var x = 0;
setInterval(function() {
changeImage()
},5000);
}
Edit
This code has been tested on my local machine and works.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var images = new Array();
for (var i = 2; i < 11; i++) {
images.push("img" + i + ".gif");
}
var x = 0;
function changeImage() {
document.getElementById('ad').src = images[x];
document.getElementById('imgsrc').innerHTML = "<h1>" + images[x] + "</h1>";
if (x < 8) {
x += 1;
} else {
x = 0;
}
}
window.onload = function() {
setInterval(function () {
changeImage();
}, 1000);
}
</script>
</head>
<body>
<img id="ad" src="img.gif" />
<div id="imgsrc"><h1>img.gif</h1></div>
</body>
</html>
Here is a fiddle of the final code working. JSFiddle doesn't like window.onload for some reason, so I had to exclude it. This doesn't really demonstrate my point, but I thought I'd just include it anyway.
Your code works to change the image src in this fiddle: http://jsfiddle.net/snB2a/1/
Try to rename your variables images and x to longer names. What can happen is, if some other code in your page, or worse, some code in one of the script file you page references, use variable "x" without declare it locally, then it would actually modify your "x" variable.
Here is an example to demonstrate the problem:
function something()
{
for (x = 0; i < 10; x++)
dosomethingelse();
}
If the above function is called in your page, then it will overwrite your "x" variable. The following code is safe:
function something()
{
var x;
for (x = 0; i < 10; x++)
dosomethingelse();
}

Image change every 30 seconds - loop

I would like to make an image change after 30 seconds. The javascript I'm using looks like this:
var images = new Array();
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 30000);
var x = 0;
function changeImage() {
document.getElementById("img").src=images[x];
x++;
}
HTML:
<img id="img" src="startpicture.jpg">
Now I haven't tested this one yet, but if my calculations are correct it will work :)
Now what I also want is to make a "fading transition" and I would like the changing of images to loop (it restarts after all the images have been shown).
Do any of you guys know how to do that?
I agree with using frameworks for things like this, just because its easier. I hacked this up real quick, just fades an image out and then switches, also will not work in older versions of IE. But as you can see the code for the actual fade is much longer than the JQuery implementation posted by KARASZI István.
function changeImage() {
var img = document.getElementById("img");
img.src = images[x];
x++;
if(x >= images.length) {
x = 0;
}
fadeImg(img, 100, true);
setTimeout("changeImage()", 30000);
}
function fadeImg(el, val, fade) {
if(fade === true) {
val--;
} else {
val ++;
}
if(val > 0 && val < 100) {
el.style.opacity = val / 100;
setTimeout(function(){ fadeImg(el, val, fade); }, 10);
}
}
var images = [], x = 0;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 30000);
You should take a look at various javascript libraries, they should be able to help you out:
mootools
jQuery
Dojo Toolkit
prototype
All of them have tutorials, and fade in/fade out is a basic usage.
For e.g. in jQuery:
var $img = $("img"), i = 0, speed = 200;
window.setInterval(function() {
$img.fadeOut(speed, function() {
$img.attr("src", images[(++i % images.length)]);
$img.fadeIn(speed);
});
}, 30000);
setInterval function is the one that has to be used.
Here is an example for the same without any fancy fading option. Simple Javascript that does an image change every 30 seconds. I have assumed that the images were kept in a separate images folder and hence _images/ is present at the beginning of every image. You can have your own path as required to be set.
CODE:
var im = document.getElementById("img");
var images = ["_images/image1.jpg","_images/image2.jpg","_images/image3.jpg"];
var index=0;
function changeImage()
{
im.setAttribute("src", images[index]);
index++;
if(index >= images.length)
{
index=0;
}
}
setInterval(changeImage, 30000);
Just use That.Its Easy.
<script language="javascript" type="text/javascript">
var images = new Array()
images[0] = "img1.jpg";
images[1] = "img2.jpg";
images[2] = "img3.jpg";
setInterval("changeImage()", 30000);
var x=0;
function changeImage()
{
document.getElementById("img").src=images[x]
x++;
if (images.length == x)
{
x = 0;
}
}
</script>
And in Body Write this Code:-
<img id="img" src="imgstart.jpg">

Categories

Resources