JavaScript slideshow stuck on first photo - javascript

I am a Javascript beginner trying to make a simple slideshow using Javascript. From the work I've done, I'm able to produce only one of the five images. The console says nothing is wrong and I am at a loss as to why the other pictures won't show.
<script>
var images = new Array();
images[0] = new Image();
images[0].src = "burger1.jpg";
images[1] = new Image();
images[1].src = "burger2.jpg";
images[2] = new Image();
images[2].src = "burger3.jpg";
images[3] = new Image();
images[3].src = "burger4.jpg";
images[4] = new Image();
images[4].src = "burger5.jpg";
var slide = 0;
function next(){
if (!document.images) {
return document.getElementById('slideshow').src = images[slide].src
}
if(slide < 5){
slide++;
} else{
slide = 0;
}
setTimeout("next()",3000);
}
next();
</script>
</head>
<body>
<img src="burger1.jpg" id="slideshow" width=100 height=100 />
P.S I do not know jquery.

if (!document.images) {
return document.getElementById('slideshow').src = images[slide].src
}
here !document.images is [object HTMLCollection] and you are checking ! of this use only :
if(slide < 5){
slide++;
} else{
slide = 0;
}
setTimeout(next,3000);
document.getElementById('slideshow').src = images[slide].src

Remove
if (!document.images) {
return document.getElementById('slideshow').src = images[slide].src
}
Add
document.getElementById('slideshow').src = images[slide].src
After setTimeout

There's more to fix in your code so I'll try to show you a better approach then just a quicky:
jsBin demo
var slideshow = document.getElementById('slideshow'), // Cache your element!
images = [ // Create an array of images paths
"burger1.jpg",
"burger2.jpg",
"burger3.jpg"
],
slide = 0,
tot = images.length; // count the total of images
for(var i=0; i<tot; i++){ // preload images (so we don't have to wait for them)
var img = new Image();
img.src = images[i];
}
function next() {
slideshow.src = images[slide++ % tot]; // Modulo operator to loop the counter
setTimeout(next, 3000); // Don't wrap `next` in String
}
next();

Related

Preloading Images in JavaScript (Need an Alert When Completed)

I have the following code below, which successfully preloads images into the browser cache when the PreloadAllImages function is called. Does anyone know how to send a simple alert, e.g. "All images have been preloaded into the browser cache." when the last image (or all images) is loaded. I have 300 images, so setTimeOut won't work for latency/download lag reasons. I've tried callbacks, placing alert commands in different places, etc... but have not been successful.
This code is based on JavaScript Only Method #1 found here. https://perishablepress.com/3-ways-preload-images-css-javascript-ajax/
function PreLoadAllImages() {
var images = new Array();
function preload() {
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image();
images[i].src = preload.arguments[i];
}
}
preload('Images/Image1.jpg', 'Images/Image2.jpg', ... , 'Images/Image300.jpg');
}
With some help, this is how the problem was solved in case anyone else needs it. Loaded images into an invisible div on the html page, then ran script to ensure everything was loaded. A button calls PreLoadAllImages() and then CheckImages().
var imagefiles = [
"Images/Image1.jpg",
"Images/Image2.jpg",
.....
"Images/Image300.jpg"];
function PreLoadAllImages () {
imagefiles.forEach(function(image){
var img = document.createElement('img');
img.src = image;
document.body.appendChild(img);});
$('img').hide();
}
var all_loaded;
function CheckImages() {
$('img').each(function(){ // selecting all image element on the page
var img = new Image($(this)); // creating image element
img.src = $(this).attr('src'); // pass src to image object
if(img.complete==false) {
all_loaded=false;
return false;
}
all_loaded=true;
return true;});
}
function CheckLoadingImages() {
var result;
var Checking=setInterval(function(){
result=CheckImages();
if(all_loaded==true) {
clearInterval(Checking);
MsgAfterLoading();
}
}, 2000);
}
function MsgAfterLoading() {
alert('All Images Loaded');
}
You could check if i is equals to the length of the array, so it will look like:
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image()
images[i].src = preload.arguments[i]
//the code
if (i == preload.arguments.length){
alert("Last image loaded");
}
//the code
}
Let me know if you have any questions.
Could you try looping through all the image elements and check the naturalWidth property, if they are all greater than 0 and its the last image then alert.
This link: Preloading Images in JavaScript (Need an Alert When Completed) should help
A promise might resolve your problem.
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise
var myPromise = new Promise( function(resolve, reject) {
// preload code
resolve(true);
};
myPromise.then(function() {
// your alert
};
You can use the onload event.
function PreLoadAllImages() {
var images = new Array();
var numberofimages = 0, loadedimages = 0;
function preload() {
numberofimages = preload.arguments.length;
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image();
images[i].src = preload.arguments[i];
images[i].onload = () => {
loadedimages++;
if(loadedimages == numberofimages){
alert("All images are loaded");
}
}
}
}
preload('Images/Image1.jpg', 'Images/Image2.jpg', ... , 'Images/Image300.jpg');
}

Uncaught TypeError: Cannot set property 'src' of undefined slideshow

I'm having a lot of trouble getting this slideshow to work. I have to make an external Javascript file. I am very confused because I don't know js very well at all. Any help will be appreciated.
var numImages = 3;
var images = [];
for (var i = 0; i < numImages; ++i) {
var image = new Image();
image.src = 'baby' + (i + 1) + '.jpg';
images.push(image);
}
var step = 0;
function slideit() {
if (! document.images) {
return;
}
document.images.slide.src = images[step].src;
step = (step + 1) % numImages;
}
setInterval(slideit, 2500);
Unless this somewhere in your HTML ...
<img id="slide">
Then this will be is undefined ...
document.images.slide
Therefore ...
document.images.slide.src = ...
Explains ...
Uncaught TypeError: Cannot set property 'src' of undefined
Here's a simplified piece of code that you can run and see it work
var images = [
'http://placehold.it/200?text=A',
'http://placehold.it/200?text=B',
'http://placehold.it/200?text=C'
]
function slideIt(elem, i, images) {
elem.src = images[i % images.length]
setTimeout(slideIt, 1000, elem, i+1, images)
}
slideIt(document.querySelector('#slideshow'), 0, images)
<img id="slideshow">
In your original code, you were preloading the images. I've made a small adaptation below to preload images first before initializing the slider.
var images = [
'http://placehold.it/200?text=A',
'http://placehold.it/200?text=B',
'http://placehold.it/200?text=C'
]
function slideIt(elem, i, images) {
elem.src = images[i % images.length].src
setTimeout(slideIt, 1000, elem, i+1, images)
}
function imagep(src) {
return new Promise(function(pass,fail) {
var i = new Image()
i.src = src
i.onload = function(event) { pass(i) }
})
}
Promise.all(images.map(imagep)).then(function(imgs) {
slideIt(document.querySelector('#slideshow'), 0, imgs)
})
<img id="slideshow">

Looping slideshow and changing animation javascript

Forgive, very very very new to Javascript. Adding in a slideshow for a project at uni, Really basic function to run to get these images to work in a slideshow,
But after it completes it exits and doesn't repeat or loop like I would like it too,
Also if i wanted to have a fade animation so its not just one image straight into next what would be the best way?
Thanks.
<-- HTML -->
<img id="Slide" src="images/okc4.jpg" width=640 height=400 />
//javascript
<script type="text/javascript">
var slideimages = new Array()
slideimages[0] = new Image()
slideimages[0].src = "image.jpg"
slideimages[1] = new Image()
slideimages[1].src = "image.jpg"
slideimages[2] = new Image()
slideimages[2].src = "image.jpg"
var step = 0;
function slideit(){
document.getElementById("Slide").src = slideimages[step].src
if (step<=2) {
step++
}else{
step=0
}
setInterval("slideit()",2500)
}
slideit()
</script>
Please see this fiddle: http://jsfiddle.net/8mdLz8tw/1/
Your index does not exist anymore, will grow to 3 and it will trow an error, also I have a made your code a bit different with an anonymous function. In the console you can see the switch and restart, since all the pictures are the same if you use lorempixel :)
var slideimages = new Array()
slideimages[0] = new Image()
slideimages[0].src = "http://lorempixel.com/640/400/"//replaced pics for fiddle
slideimages[1] = new Image()
slideimages[1].src = "http://lorempixel.com/640/400/"
slideimages[2] = new Image()
slideimages[2].src = "http://lorempixel.com/640/400/"
var step = 0;
setInterval(function () {
document.getElementById("Slide").src = slideimages[step].src;
if (step < 2) {//Here was your mistake, if you increase when it is exactly 2 your step will go to three and thus throw an error since you don't have an image indexed with three
step++;
console.log(step);
console.log("switched");
} else {
step = 0;
console.log("restart");
}
}, 2000);
Try:
var slideimages = new Array()
slideimages[0] = new Image()
slideimages[0].src = "image.jpg"
slideimages[1] = new Image()
slideimages[1].src = "image.jpg"
slideimages[2] = new Image()
slideimages[2].src = "image.jpg"
var step = 0;
function slideit(){
document.getElementById("Slide").src = slideimages[step].src
if (step<2) {
step++
}else{
step=0
}
}
setInterval(function(){slideit();},2500)
setInterval is enough to make the function execute every 2.5 seconds.
Link: https://jsfiddle.net/rafaelropota/7qr7qnsx/1/
To make it loop, like you wished, you have to set it to 0 when step reaches a size 1 smaller then the length of the array.
var slideimages = new Array()
slideimages[0] = new Image()
slideimages[0].src = "image.jpg"
slideimages[1] = new Image()
slideimages[1].src = "image2.jpg"
slideimages[2] = new Image()
slideimages[2].src = "image3.jpg"
var step = 0;
function slideit(){
document.getElementById("Slide").src = slideimages[step].src
if (step < slideimages.length-1) {
step++
}else{
step=0
}
}
setInterval(slideit,2500)
See fiddle:
http://jsfiddle.net/bneb2bpw/2/
I think the other answers have covered the loop - but about what you said about a fading transition...
I'd use jQuery to create this effect.
Take a look at jQuery's animate() , that's the most commonly used method.
However, sometimes I like to make my own transition by using two other jQuery methods - fadeIn() and fadeOut().
window.onload = function () {
setInterval(function () {
$("#Slide").fadeOut(2000, function () {
$("#Slide").attr("src", slideimages[i].toString());
$("#Slide").fadeIn();
});
i++;
if (i >= 2) i = 0;
}, 2500);
};
This fades out the image element, and once it has faded out, changes it's source like you were doing before.
After the source has changed, it fades back in - giving a 'fade transition' effect! Working example - here
I don't think that you need to create new Image object to change src elements. Also setInterval() is not used as it intended.
<img id="Slide" src="images/okc4.jpg" width=640 height=400 />
//javascript
<script type="text/javascript">
var slideimages = ["image.jpg","image.jpg","image.jpg"];
var step = 0;
function slideit(){
document.getElementById("Slide").src = slideimages[step]
if (step<slideimages.length) {
step++
}else{
step=0
}
setInterval(slideit,2500)
}
slideit()
</script>

Using offsetx and offsettop in JavaScript or position x and positon y

I have a slider that starts at click on button and I want every image to be loaded at a offset of 200 px in comparison with the previous one. Here is the code:
var image1 = new Image()
image1.src = "img0.jpg"
var image2 = new Image()
image2.src = "img1.jpg"
var image3 = new Image()
image3.src = "img2.jpg"
var image4 = new Image()
image4.src = "img3.jpg"
var image5 = new Image()
image5.src = "img4.jpg"
var step = 1
function slideit() {
document.images.slide.src = eval("image" + step + ".src")
if (step < 5)
step++
else
step = 1
setTimeout("slideit()", 500)
}
<button onclick="slideit()">Try it</button>
<img src="img0.jpg" name="slide" width="100" height="100" position = "absolute">
I'd like to do this in JavaScript as I do not want to use jQuery in my code.
I actually don't get whats your question. Maybe you should be a bit more precise.
If you want to make a picture slider, then your approach doesn't seems to be right.
Hey this should work for you. I didn't had time to check it, so I hope there are no mistakes in it.
Just update the JS, you can leave the html.
Regards
var images = [
'image1.jpg',
'Image2.jpg',
'...'
];
function slideit()
{
var index = 0;
var container = document.getElementById('yourContainer');
var addPic = function()
{
var img = document.createElement('img');
img.src = images[index];
img.style.position = 'absolute';
img.style.left = index * 200 + 'px';
container.appendChild(img);
index++;
}
setInterval(addPic, 1000);
}

JS basic random image select

I've only started HTML yesterday and I'm trying to do a really basic memory game. First, there's an image of all the pieces, then a button that calls a function that hides that image and make another appear. This second image is a blank page with the spaces where the parts of the former image were. Also, there's an usemap and a function that returns if the player has clicked correctly or not. My problem is to come up with a function (and how to call it) to select a random part of the image.
function checkAnswer(a) {
if (a=='6') {
alert('Correct!')
}
else {
alert('Wrong!')
}
}
The 'a' must be a random number and follow the index of the chosen picture.
This is what I've found, but couldn't use:
<!-- Attempt of random
function random_imglink() {
var cobras=new Array()
cobras[1]="<img src ="..\images\Cobra1.jpg">"
cobras[2]="..\images\Cobra2.jpg"
cobras[3]="..\images\cobra3.jpg"
cobras[4]="..\images\cobra4.jpg"
cobras[5]="..\images\cobra5.jpg"
cobras[6]="..\images\cobra6.jpg"
cobras[7]="..\images\cobra7.jpg"
cobras[8]="..\images\cobra8.jpg"
cobras[9]="..\images\cobra9.jpg"
cobras[10]="..\images\cobra10.jpg"
cobras[11]="..\images\cobra11.jpg"
cobras[12]="..\images\cobra12.jpg"
cobras[13]="..\images\cobra13.jpg"
cobras[14]="..\images\cobra14.jpg"
cobras[15]="..\images\cobra15.jpg"
var ry=Math.floor(Math.random()*cobras.length)
if (ry=='0') {
ry = '1'
}
document.write('<img src="'+myimages[ry]+'" border=0>')
}
-->
<!-- Attempt of random
<script>
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = '..\images\Cobra1.jpg';
imgArray[1] = new Image();
imgArray[1].src = '..\images\Cobra2.jpg';
imgArray[2] = new Image();
imgArray[2].src = '..\images\cobra3.jpg';
function nextImage(element)
{
var img = document.getElementById(element);
for(var i = 0; i < imgArray.length;i++)
{
if(imgArray[i].src == img.src)
{
if(i === imgArray.length){
document.getElementById(element).src = imgArray[0].src;
break;
}
document.getElementById(element).src = imgArray[i+1].src;
break;
}
}
}
</script>

Categories

Resources