Making a simple photo slideshow using JavaScript, CSS and HTML - javascript

When I run it, the 1st image appears and after one second all I could see is a white blank screen. Nothing happens. I guess there's a problem in JavaScript code.
Here's the code I tried..
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">
img {
width: 582px;
height: 306px;
}
</style>
</head>
<body>
<img src="image-slider-1.jpg" id="myphoto" />
<script type="text/javascript">
var image=document.getElementById("myphoto");
var imageArray=("image-slider-1.jpg","image-slider-2.jpg","image-slider-3.jpg","image-slider-4.jpg","image-slider-5.jpg");
var imageIndex=0;
function slide(){
image.setAttribute("src",imageArray [imageIndex] );
imageIndex++;
if(imageIndex>=imageArray.length) {
imageIndex=0;
}
}
setInterval(slide,1000);
</script>
</body>
</html>
Any help is greatly appreciated.

Try this. It worked for me.
var speed = 3700; //interval
var Pic = new Array();
Pic[0] = 'abc.jpg';
Pic[1] = 'def.jpg';
Pic[2] = 'ghi.jpg';
//add as many as you want
var t; //interval
var j = 0;
var p = Pic.length;
var preLoad = new Array()
for (i = 0; i < p; i++)
{
preLoad[i] = new Image();
preLoad[i].src = Pic[i];
}
// call this from your html as shown below
//<body onload="runBGSlideShow()">
function runBGSlideShow(){
if (document.body)
{
document.body.background = Pic[j];
j = j + 1;
if (j > (p-1))
{
j=0; //start from pic1 again
}
t = setTimeout('runBGSlideShow()', speed);
}
}

The following line is not doing what you expect:
var imageArray=("image-slider-1.jpg","image-slider-2.jpg","image-slider-3.jpg","image-slider-4.jpg","image-slider-5.jpg");
if you check the value of imageArray after this call, you will find just a string, containing "image-slider-5.jpg". (Why? See the workings of the comma operator in javascript.)
To properly declare an array of strings, use the [] notation:
var imageArray=["image-slider-1.jpg","image-slider-2.jpg","image-slider-3.jpg","image-slider-4.jpg","image-slider-5.jpg"];

Related

I have trouble hiding elements in my game if they don't match

I am working on a memory game and I asked a previous question earlier which was answered. I've had this problem and I haven't been able to find a solution with effort. So it's a memory game and when the cards are clicked, they are pushed into an array which can hold two elements at max (you can only click two cards) and then the two elements' frontSrc is checked if they are the same. I set that using an expando property. If so, have them visible and then clear the array so I can do more comparisons. However, it doesn't seem to be working as intended. I'll attach a video below. I've tried using timeout to set the length again, but that didn't work. It works for the first cards, but the other ones after that, it doesn't work.
Here is my code.
<!DOCTYPE html>
<!--
Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
Click nbfs://nbhost/SystemFileSystem/Templates/Other/html.html to edit this template
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.card{
width: 35%;
}
#cards{
display: grid;
grid-template-columns:25% 25% 25% 25%;
row-gap: 25px;
}
</style>
</head>
<body onload="init()">
<section id="cards">
</section>
<script>
var arrCards = [];
var arrShowedCards = [];
//appendElements();
function init(){
createCards();
shuffleCards();
appendElements();
}
function createCards(){
var arrCardNames = ["Mouse","Penguin","Pop","Mouse","Penguin","Pop"];
for(var i = 0; i<6; i++){
var card = document.createElement("IMG");
card.src = "Images/red_back.png";
card.className = "card";
card.frontSrc = "Images/" + arrCardNames[i] + ".png";
card.id = "card" + i;
card.addEventListener("click", showCard);
document.getElementById("cards").appendChild(card);
arrCards.push(card);
}
}
function shuffleCards(){
for (let i = arrCards.length-1; i > 0; i--)
{
const j = Math.floor(Math.random() * (i + 1));
const temp = arrCards[i];
arrCards[i] = arrCards[j];
arrCards[j] = temp;
}
return arrCards;
}
function appendElements(){
for(var i = 0; i<arrCards.length; i++){
document.getElementById("cards").appendChild(arrCards[i]);
}
}
function showCard(){
var sourceString = "Images/red_back.png";
this.src = this.frontSrc;
arrShowedCards.push(this);
if(arrShowedCards.length === 2){
if(arrShowedCards[0].frontSrc === arrShowedCards[1].frontSrc){
console.log("Match!");
arrShowedCards = [];
}
else{
console.log("No match!");
setTimeout(function(){
arrShowedCards[0].src = sourceString;
arrShowedCards[1].src = sourceString;
}, 1000);
}
}
}
</script>
</body>
</html>
I am not sure how come it doesn't work for it for the other cards.
Here is the video.
https://drive.google.com/file/d/1aRPfLALHvTKjawGaiRgD1d0hWQT3BPDQ/view
If anyone finds a better way to approach this, let me know.
Thanks!
I think when not match, you need to reset arrShowedCards otherwise its length will be greater than 2 forever.
function showCard() {
var sourceString = "Images/red_back.png";
this.src = this.frontSrc;
arrShowedCards.push(this);
if (arrShowedCards.length === 2) {
var a = arrShowedCards[0], b = arrShowedCards[1];
arrShowedCards.length = 0;
if (a.frontSrc === b.frontSrc) {
console.log("Match!");
} else {
console.log("No match!");
setTimeout(function () {
a.src = sourceString;
b.src = sourceString;
}, 1000);
}
}
}

Image Changing Button using JavaScript

I had a look here and here for my answer but found that the code was far too long for such a simple process.
Below, my code shows a basic Image Changer by having the 'image' changed to the different .jpg's in an array, located in the same file.
<!DOCTYPE html>
<html>
<body>
<img id="image" src="blank_light.jpg" style="width:100px">
<p></p>
<button class = "change-image">Change Lights</button>
<script>
var imageSources = ["green_light.jpg", "yellow_light.jpg", "red_and_yellow_light.jpg", "red_light.jpg", "blank_light.jpg"]
var buttons = document.getElementsByClassName("change-image")
for (let i = 0; i < buttons.length; i++) {
buttons[i].onclick = function () {
document.getElementById("image").src = imageSources[i]
}
}
</script>
</body>
</html>
In theory, because I've embedded the script within the HTML it should work like a dream, but the image seems to get stuck on the yellow light. Is there a repeat button click phase I'm missing?
Thanks.
There is no need to use a loop. You can get reference to the button using document.getElementsByClassName("change-image")[0];. Then you can add an event lister to trigger on each button click.
Each time a user clicks you iterate through the array by one.
You could look at doing something like this:
var buttons = document.getElementsByClassName("change-image")[0];
var index = 0;
buttons.addEventListener('click',function() {
if(index === imageSources.length ) {
index = 0;
}
document.getElementById("image").src = imageSources[index];
index++;
});
Here is the complete code, which works. If you inspect the img element you will see that it updates.
<!DOCTYPE html>
<html>
<body>
<img id="image" src="blank_light.jpg" style="width:100px">
<p></p>
<button class="change-image">Change Lights</button>
<script>
var imageSources = ["green_light.jpg", "yellow_light.jpg", "red_and_yellow_light.jpg", "red_light.jpg", "blank_light.jpg"]
var buttons = document.getElementsByClassName("change-image")[0];
var index = 0;
buttons.addEventListener('click', function() {
if (index === imageSources.length) {
index = 0;
}
document.getElementById("image").src = imageSources[index];
index++;
});
</script>
</body>
</html>
Funny implementation -))
document.getElementById("changer").addEventListener("click", function(){
var i = document.getElementById("source");
var images = [
"http://lorempixel.com/400/200/sports",
"http://lorempixel.com/400/200/animals",
"http://lorempixel.com/400/200/nature"
];
var ord = parseInt(i.dataset.order);
nextImage = function(prev) {
return (prev+1 >= images.length ? (prev + 1)%images.length : prev+1);
}
document.getElementById("source").src = images[nextImage(ord)];
i.dataset.order = ord + 1;
})
<img id="source" data-order="0" src="http://lorempixel.com/400/200/sports">
<button id="changer">change</button>

How can I make 6 images play as a gif with an on click button (Can't find whats missing in my code)

So I'm trying to get an 6 images to play (runner0 - runner5) and then go back to the beginning and so far only the first image and second image appears but the rest aren't playing but are in the same folder. I was told to use getElementById(), getElementsByName(), or getElementsByTagName(). But how would i implement those?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Project 10 11 Sample</title>
<script type="text/javascript">
<!-- HIDE FROM INCOMPATIBLE BROWSERS
var curPennant = 1;
var begin;
pennant1 = new Image();
pennant1.src = "runner0.jpg";
pennant2 = new Image();
pennant2.src = "runner1.jpg";
pennant3 = new Image();
pennant3.src = "runner2.jpg";
pennant4 = new Image();
pennant4.src = "runner3.jpg";
pennant5 = new Image();
pennant5.src = "runner4.jpg";
pennant6 = new Image();
Pennant6.src = "runner5.jpg";
function wave() {
if (curPennant == 1) {
document.images[0].src = pennant2.src;
curPennant = 2;
}
else {
document.images[0].src = pennant1.src;
curPennant = 1;
}
}
function startWaving() {
if (begin)
clearInterval(begin);
begin = setInterval("wave()",500);
}
// STOP HIDING FROM INCOMPATIBLE BROWSERS -->
</script>
</head>
<body>
<p>
<img alt="" height="132" src="runner0.jpg" width="107" /></p>
<p><input type="button" value=" Wave"
onclick="startWaving();" /><input type="button" name="stop"
value=" Stop" onclick="clearInterval(begin);" /></p>
</body>
</html>
The easiest way would be to use an array and loop through it. First instantiate an array and add all your images to it, which is very easy because you named them with same names and ascending numbers.
So instead of:
var curPennant = 1;
pennant1 = new Image();
pennant1.src = "runner0.jpg";
pennant2 = new Image();
pennant2.src = "runner1.jpg";
pennant3 = new Image();
pennant3.src = "runner2.jpg";
pennant4 = new Image();
pennant4.src = "runner3.jpg";
pennant5 = new Image();
pennant5.src = "runner4.jpg";
pennant6 = new Image();
Pennant6.src = "runner5.jpg";
say:
var current = 0;
var imageArray = [];
for(i = 0; i < 6; i++){
var img = new Image();
img.src = "runner"+i+".jpg";
imageArray.push(img);
}
and in your function wave use:
function wave(){
document.images[0].src = imageArray[current++%imageArray.length].src;
}
If you just need the source names and don't need the Images (pennant1 and so on) for anything else, you could even simplify it more:
var current = 0;
var imageArray = [];
for(i = 0; i < 6; i++){
imageArray.push("runner"+i+".jpg");
}
and
function wave(){
document.images[0].src = imageArray[current++%imageArray.length];
}
NOTE: You also set the interval with:
begin = setInterval(wave, 500);
working fiddle (i just set the file name as content of a paragraph, instead you need to assign it as the source of your image)

Javascript SetTimeout chaining

This may be a simple problem but I can't seem to embed a variable parameter in a function for future execution. "alert" is the function I'd like to delay execution, with the parameter 0, 1, 2 etc
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script language="JavaScript">
var init = function init() {
for (var i = 0, max = 3; i < max; i++) {
var then;
then = (function(jj) {
return jj;
}(i));
var pp = function(jj) {
return alert(then);
};
setTimeout(function() {
pp();
}, then * 1000);
}
};
</script>
</head>
<body onload="init();">
<button onclick="init();"></button>
</body>
</html>
You didn't really ask a question so I'll assume any implementation that produces the results you were expecting is what you want.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script language="JavaScript">
function createfunc(i) {
return function() { alert(i); };
}
var init = function init() {
for (var i = 0, max = 3; i < max; i++) {
var func = createfunc(i);
setTimeout(func, i * 1000);
}
};
</script>
</head>
<body onload="init();">
<button onclick="init();"></button>
</body>
</html>
This will alert a number, then wait a second and alert another number. Until 3 is reached:
var init = function() {
var counter = 0, //Start
max = 3 //End
var count = function() {
alert(counter) //Alert
if ( counter < max ) { //If we havent reached 3 then queue this function to be called again
window.setTimeout(function() {
count()
}, 1000)
}
counter++
}
count() //Start the counter
}
Here is a fiddle: http://jsfiddle.net/EXwH2/1/
You enclosed the first function in a closure but not the second, so you essentially set your pp var to the last iteration before setTimeout is called for the first time. What's your intent with the then variable? If you want to stagger the calls, each with their own value, you might want to put the call to setTimeout itself within its own closure:
var init = function init() {
for (var i = 0, max = 3; i < max; i++) {
(function (jj) {
setTimeout(function() {
alert(jj);
}, jj * 1000);
})(i);
}
};

Problem with putting in the right parameters

I have problem with putting in the right parameters from an eventListener into a function.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
window.onload = function() {
var galleryContainer = document.getElementById('galleryContainer');
var image = galleryContainer.getElementsByTagName('div');
//console.log(image);
var images = new Array();
images.push(image);
for(var i = 0; i < images[0].length; i++) {
images[0][i].addEventListener('click', function() {showImage(this)
}, false);
};
}
// I dont know with parameter to put into showImage() from the listener.
function showImage( here is the problem ) {
var preview = document.getElementById('preview');
preview.innerhtml = image.innerhtml;
// I want to put the image into the preview element.
}
</script>
</head>
<body>
<div id="galleryContainer">
<div>trams</div>
<div>trams</div>
<div>trams</div>
<div>trams</div>
</div>
<div id="preview" style="width: 200px; height: 200px; border: 1px solid red"></div>
</body>
Try this code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
window.onload = function() {
var galleryContainer = document.getElementById('galleryContainer');
var images = galleryContainer.getElementsByTagName('div');
//console.log(images);
for(var i = 0; i < images.length; i++) {
images[i].addEventListener('click', showImage, false);
};
}
// I dont know with parameter to put into showImage() from the listener.
function showImage(ev) {
ev=ev||event; // ev now point to click event object
var preview = document.getElementById('preview');
preview.innerHTML = this.innerHTML; // this point to DIV(trams)
}
</script>
</head>
<body>
<div id="galleryContainer">
<div>trams1</div>
<div>trams2</div>
<div>trams3</div>
<div>trams4</div>
</div>
<div id="preview" style="width: 200px; height: 200px; border: 1px solid red"></div>
</body>
Working example http://jsfiddle.net/Cp6HJ/
window.onload = function() {
var galleryContainer = document.getElementById('galleryContainer');
var image = galleryContainer.getElementsByTagName('div');
//console.log(image);
var images = new Array();
images.push(image);
for(var i = 0; i < images[0].length; i++) {
var callback = function(item){ return function(){ showImage(item); }; }(images[0][i]);
images[0][i].addEventListener('click', callback, false);
};
};
function showImage( item ) {
var preview = document.getElementById('preview');
preview.innerHTML = item.innerHTML;
}
Use this for the function definition statement :
function showImage(image) {
...
}
And correction in the inner html statement:
(note the capitalized 'H')
preview.innerHTML = image.innerHTML;

Categories