Problem with image 'rotations' within a div element - javascript

I'm using the code below to create a 'rotation' of images for display on a website. I wish for the images to display within a 'div' element...and i'm having trouble accomplishing that. It seems the problem is when I attempt to set each image as the 'background image' for the element (the line that reads "document.getElementById("rotation").style.backgroundImage = "url(toString(ImgName[number]))";). Only the initial image displays, without any 'rotation' of other images. Any help appreciated, this is becoming very frustrating.
<!DOCTYPE html>
<html>
<title>test page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<head>
<style>
div.rotation {
height: 256px;
width: 100%;
padding: 0px;
background-color: powderblue;
border-style: solid;
border-width: 5px;
border-radius: 25px;
}
</style>
</head>
<body>
<div class="w3-quarter">
<div class="w3-padding-small">
<div class="w3-center">
<div class="rotation">
<p>
<img src='images/rotation/LA_Panel.png' id='rotateImg0' alt='image rotation' />
<img src='images/rotation/McCulloch_256.png' id='rotateImg1' style='display:none;' alt='image rotation' />
<img src='images/rotation/MO_Panel.png' id='rotateImg2' style='display:none;' alt='image rotation' />
<img src='images/rotation/Rommel.png' id='rotateImg3' style='display:none;' alt='image rotation' />
</p>
</div>
</div>
</div>
</div>
</body>
</html>
<script type='text/javascript'>
var rotation = function () {
var currentImage,
images = [],
ImgName = [],
count,
hideImages,
showImage,
fn;
count = (function () {
// Figure out how many images we have on the rotation
var x = 0;
while (document.getElementById('rotateImg' + (x + 1).toString())) {
images[x] = document.getElementById('rotateImg' + x.toString());
ImgName[x] = document.getElementById('rotateImg' + x.toString()).src;
x++;
}
return images.length;
})();
hideImages = function () {
// Hide all the images
for (var i = 0; i < count; i++) {
images[i].style.display = 'none';
}
};
showImage = function (number) {
document.getElementById("rotation").style.backgroundImage = "url(toString(ImgName[number]))";
images[number].style.display = 'block';
};
fn = {};
fn.setupRotation = function () {
// Show the first image
currentImage = 0;
showImage(currentImage);
// Start the rotation
var interval = setInterval(rotation.advanceRotation, 4000);
};
fn.advanceRotation = function () {
if (currentImage + 1 == count)
currentImage = 0;
else
currentImage++;
hideImages();
showImage(currentImage);
};
return fn;
} ();
rotation.setupRotation();
</script>

One thought might be to pluck off the first child and slam him to the end of the line.
let images = document.querySelector('#images');
setInterval(() => {
let el = images.removeChild(images.childNodes[0]);
images.appendChild(el);
}, 1000);
#images {
font-size: 0;
}
.img {
display: inline-block;
width: 30px;
height: 30px;
}
<div id="images">
<div class="img" style="background-color: red"></div>
<div class="img" style="background-color: orange"></div>
<div class="img" style="background-color: yellow"></div>
<div class="img" style="background-color: green"></div>
<div class="img" style="background-color: blue"></div>
</div>

Related

Image change with toggle

Been working on a home automation dashboard and I need some help. How do I get the image to change when the button is toggled ON and OFF. I have a sun svg for on and moon svg for off.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dashboard</title>
<!-- Add font from Google fonts -->
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght#300&display=swap" rel="stylesheet">
<!-- Link CSS style sheet to html document -->
<link rel="stylesheet" href="style.css">
<!-- Link JavaScript file to html document -->
<script src="mqttws31.js"></script>
<script src="dashboard.js"></script>
</head>
<body>
<div class="header">
<h1>Home Automation Dashboard</h1>
</div>
<hr>
<div id="messages"></div>
<div id="status"></div>
<hr>
<ul class="dashboard">
<ol class="b">
<li class="dashboard_item kitchen">
<img src="./moon.svg" width="40px" height="40px" alt="">
<h4>Kitchen</h4>
<p id="kitchen-light">OFF</p>
<button id="kitchen-btn">Toggle</button>
</li>
<ol class="b">
<li class="dashboard_item frontdoor" >
<img src="./door-closed.svg" width="40px" height="40px" alt="">
<h4>Front Door</h4>
<p>CLOSED</p>
</li>
</ul>
</body>
</html>
<!-- variable in js -->
var KitchenState = true;
var el = document.getElementById("kitchen-btn");
el.addEventListener('click', function() {
document.getElementById("kitchen-light").innerHTML = KitchenState ? "ON" : "OFF";
KitchenState = !KitchenState;
});
Been trying examples online with no luck so far.
Give some id attribute to the image and then change it in the same way like you are changing the innerHTML. For image you just need to change the src accordingly.
<script>
var KitchenState = true;
var el = document.getElementById("kitchen-btn");
el.addEventListener('click', function() {
document.getElementById("kitchen-light").innerHTML = KitchenState ? "ON" : "OFF";
document.getElementById('toggle-img').src = KitchenState ? './sun.svg' : './moon.svg'
KitchenState = !KitchenState;
});
</script>
<img src="./moon.svg" width="40px" id="toggle-img" height="40px" alt="">
use .setAttribute or .src
add id kitchen-icon to tag <img> icon
and try code:
var KitchenState = true;
var el = document.getElementById("kitchen-btn");
el.addEventListener('click', function() {
document.getElementById("kitchen-light").innerHTML = KitchenState ? "ON" : "OFF";
document.getElementById('kitchen-icon').src = KitchenState ? './moon.svg' : './sun.svg'
KitchenState = !KitchenState;
})
From the point of view of your question, I think you need the following code
let btnAll = document.getElementByTagName('button')
let conAll = document.getElementByClassName('content')
let btnAllLen = btnAll.length
//Create a callback function for the click event of each button
for (let i = 0; i < btnAllLen; i++) {
!(function(n) { // Register click events
btnAll[n].addEventListener('click', function() {
for (let j = 0; j < btnAlllen; j++) {
btn[j].className = ""
conAll[j].style.display = "none"
}
this.className = "active"
conAll[n].style.display = "block"
})
})(i)
}
.main {
text-align: center;
}
button:focus {
outline: none;
}
nav {
margin-top: 30px;
box-sizing: border-box;
}
button {
background: white;
border: none;
height: 36px;
line-height: 36px;
width: 80px;
text-align: center;
border: 1px solid lightgray;
border-radius: 4px;
cursor: pointer;
}
nav>button:not(:first-child) {
margin-left: 15px;
}
.active {
background: black;
color: white;
}
.content {
margin-top: 40px;
}
.content>p {
display: none;
}
<div class="main">
<nav>
<button class="active">content 1</button>
<button>content 2</button>
<button>content 3</button>
<button>content 4</button>
</nav>
<div class="content">
<p style="display: block;">content1</p>
<p>content2</p>
<p>content3</p>
<p>content4</p>
</div>
</div>

Getting multiple a sound and countdown timer to work using the same button

So I'm trying to implement sound into my program that whenever you click the start button, it starts both the sound and the count down at the same time, but currently, it only starts the time. I've gotten it to work by itself without the timer but every time I try to connect it using addEventListener it just doesn't seem to connect to the sound. Does anyone see anything I'm missing or am I using it wrong?
This is my HTML
<!DOCTYPE html>
<html>
<head>
<link href="cssstyle.css" rel="stylesheet" type="text/css" />
<script src="loopv3.js"></script>
<link href="Password.html" />
</head>
<body>
<audio id="sound" ; src="us-lab-background.mp3"></audio>
<div id="under" style="position: absolute">
<img
src="https://cdn.mos.cms.futurecdn.net/M7fDTpDnJcZ4dt3myngzxi.jpg"
alt="space background"
width="100%"
height="100%"
/>
</div>
<div id="countdowntimer" style="left: 44%; top: 105%; position: absolute">
<p id="countDown" ; style="color: white">Seconds till Blast Off!</p>
</div>
<div id="top" style="left: 41%; top: 60%; position: absolute">
<img
src="https://images-platform.99static.com/VMvW_L-joavx2q3oj5fSTZOiGwI=/0x0:1000x1000/500x500/top/smart/99designs-contests-attachments/114/114579/attachment_114579370"
alt="UAT Space Logo"
width="45%"
height="50%"
/>
</div>
<div id="countdowntimer" style="left: 43.5%; top: 110%; position: absolute">
<p id="timer"></p>
<button onclick="countDown()">Start Countdown!</button>
</div>
<div id="text" style="left: 20%; top: 97%; position: absolute">
<b style="color: white">Rocket Launch Timer.</b>
</div>
<button id="stopTime" onclick="stopCount()">Stop!</button>
</body>
</html>
this is my JavaScript
var timedown;
var x = document.getElementById('sound');
x.addEventListener('click', countDown);
x.addEventListener('click', noise);
function countDown() {
var currTime = 55;
timedown = setInterval(function () {
currTime = currTime - 1;
document.getElementById('countdowntimer').innerHTML =
'The time is:' + currTime;
if (currTime == 0) {
clearInterval(timedown);
document.getElementById('countdowntimer').innerHTML = 'BLASTOFF!';
} else if (currTime <= 25) {
document.getElementById('countdowntimer').innerHTML =
'Half way to launch ' + currTime;
}
}, 1000);
}
function stopCount() {
clearInterval(timedown);
}
function noise() {
var sound = document.getElementById('countdowntimer');
sound.play();
}
You cannot add two eventlisteners on the same element with the same event. The previous one will be discarded. Instead create a new function which will call the other two functions on event. Eg
x.addEventListener("click", ()=>{ countDown(); noise();});
More Information about this is here
First issue - in your function noise(), you have it getting the element "countdowntimer". Remove this all together, and replace sound.play(); with x.play(); as you already define var x = document.getElementById("sound");
Next, create a new function to call both countDown() and noise()
I've replaced the audio in this snippet so I could test it.
var timedown
var x = document.getElementById("sound");
x.addEventListener("click", countDown);
x.addEventListener("click", noise);
var currTime = 55
function activate() {
countDown();
noise();
}
function countDown() {
timedown = setInterval(function() {
currTime = currTime - 1;
document.getElementById("countdowntimer").innerHTML = "The time is:" + currTime;
if (currTime == 0) {
clearInterval(timedown);
document.getElementById("countdowntimer").innerHTML = "BLASTOFF!"
} else if (currTime <= 25) {
document.getElementById("countdowntimer").innerHTML = "Half way to launch " + currTime;
}
}, 1000);
};
function stopCount() {
clearInterval(timedown)
x.pause();
};
function noise() {
x.play();
};
<html>
<head>
<link href="cssstyle.css" rel="stylesheet" type="text/css">
<script src="loopv3.js"></script>
<link href="Password.html">
</head>
<body>
<audio id="sound" ; src="https://sounds-mp3.com/mp3/0011247.mp3"></audio>
<div id="under" style="position: absolute">
<img src="https://cdn.mos.cms.futurecdn.net/M7fDTpDnJcZ4dt3myngzxi.jpg" alt="space background" width="100%" height="100%"> </div>
<div id="countdowntimer" style="left:44%; top: 105%; position: absolute">
<p id="countDown" ; style="color:white"> Seconds till Blast Off!</p>
</div>
<div id="top" style="left: 41%; top: 60%; position: absolute">
<img src="https://images-platform.99static.com/VMvW_L-joavx2q3oj5fSTZOiGwI=/0x0:1000x1000/500x500/top/smart/99designs-contests-attachments/114/114579/attachment_114579370" alt="UAT Space Logo" width="45%" height="50%"> </div>
<div id="countdowntimer" style="left: 43.5%; top: 110%; position: absolute">
<p id="timer"></p>
<button onclick='activate()'>Start Countdown!</button>
<div id="text" style="left: 20%; top: 97%; position: absolute">
<b style="color:white">Rocket Launch Timer.</b>
</div>
<button id="stopTime" onclick='stopCount()'>Stop!</button>
</body>
</html>

JavaScript - periodically change "active" image

I have 4 pictures and want them to periodically change class (I have .active class, which is similar to hover).
.active,
.pic:hover{
position: absolute;
border: 1px solid black;
transform: scale(1.1);
transition: transform .2s;
}
Basically I need the first picture to have the class active and after some time change it so the next picture has the class and the first one lose it.
Is something like that even possible?
Picture in HTML:
<div class="products">
<a href="http://example.com/produkt1">
<img class="pic" src="image.jpg" alt="image" width="75" height="75">
</a>
</div>
and JS:
productIndex = 0;
slideshow();
function slideshow(){
var i;
var pic = document.getElementsByClassName("pic");
for(i = 0; i < pic.length; i++){
pic[i].className = pic[i].className.replace("active", "");
}
productIndex++;
if(productIndex > pic.length){
productIndex = 1;
}
pic[productIndex-1].className += active;
setInterval(slideshow, 2000);
}
You can use setInterval to run a function periodically that will change the active class. Something like this (psuedo-code):
var imageArray = [];
var activeIndex = 0;
setInterval(function(){
imageArray[activeIndex].removeClass('active');
activeIndex++;
activeIndex %= 4;
imageArray[activeIndex].addClass('active');
}, 5000);
The number value passed in as a parameter is how many milliseconds to wait before running the function again. In this example, 5 seconds will pass between the classes are changed.
setInterval Reference
This is ugly but it could work for super basic ... You just need to update the div blocks with images if necessary. Uses jquery...
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<style>
div {
width:50px;
height:50px;
background-color: black;
margin-bottom:10px;
}
.active {
background-color: red;
}
</style>
</head>
<body>
<div id="pic1"></div>
<div id="pic2"></div>
<div id="pic3"></div>
<div id="pic4"></div>
<script>
let lastActive = 0;
setInterval(()=>{
$('div').removeClass('active');
if(lastActive === 0){
$('#pic1').addClass('active');
lastActive = 1;
}
else if(lastActive === 1){
$('#pic2').addClass('active');
lastActive = 2;
}
else if(lastActive === 2){
$('#pic3').addClass('active');
lastActive = 3;
}
else if(lastActive === 3){
$('#pic3').addClass('active');
lastActive = 4;
}
else if(lastActive === 4){
$('#pic1').addClass('active');
lastActive = 1;
}
}, 500)
</script>
</body>
</html>
Matt L. has a good point here. Your code has the setInterval inside your slideshow function, otherwise it's fine.
productIndex = 0;
slideshow();
function slideshow(){
var i;
var pic = document.getElementsByClassName("pic");
for(i = 0; i < pic.length; i++){
pic[i].className = pic[i].className.replace("active", "");
}
productIndex++;
if(productIndex > pic.length){
productIndex = 1;
}
pic[productIndex-1].className += active;
}
setInterval(slideshow, 2000);
could probably work. Matt's answer is a lot better, and I came up with something similar, which is testable on jsfiddle.
You could do it like this for example:
$(document).ready(function() {
setInterval(function() {
var active = $('.active');
active.nextOrFirst().addClass('active');
active.removeClass('active');
}, 3000);
});
$.fn.nextOrFirst = function(selector)
{
var next = this.next(selector);
return (next.length) ? next : this.prevAll(selector).last();
};
.active,
.pic:hover{
border: 1px solid black;
}
.pic {
width: 150px;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="image-container">
<img class="pic active" src="https://via.placeholder.com/350x150">
<img class="pic" src="https://via.placeholder.com/350x150">
<img class="pic" src="https://via.placeholder.com/350x150">
<img class="pic" src="https://via.placeholder.com/350x150">
</div>
Edit:
This, instead of most other solutions, will work with any amount of items. To use it only on pictures just specify via selector in the function.
Checkout this working example. I've made use of a combination of setInterval and setTimeout.
$(window).ready(()=>{
// get all the images inside the image-container div
let $images = $('.image-container').find('.image');
let currImage = 0;
// execute this code every 2 seconds
window.setInterval(()=>{
// add the active class to the current image
$($images[currImage]).addClass('active');
setTimeout(()=>{
// execute the code here after 1.5 seconds
// remove the active class from the previous image
$($images[currImage-1]).removeClass('active');
}, 1500);
// make sure we don't go over the number of elements in the collection
currImage = currImage >= $images.length ? 0 : currImage + 1;
}, 2000);
});
.image.active {
border: thin solid blue;
}
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<div class="image-container" class="">
<img src="https://via.placeholder.com/200x200" class="image active">
<img src="https://via.placeholder.com/200x200" class="image">
<img src="https://via.placeholder.com/200x200" class="image">
<img src="https://via.placeholder.com/200x200" class="image">
</div>
Do make sure that the code in setTimeout will execute before the next interval. Meaning, the time set for setTimeout is always less than setInterval's :)
Yes it is possible:
function carousel() {
var images = document.querySelectorAll(".container img");
for(var i = 0; i < images.length; i++) {
if(images[i].classList.contains("active")) {
images[i].classList.remove("active");
if(i == images.length - 1) {
images[0].classList.add("active");
} else {
images[i + 1].classList.add("active");
}
break;
}
}
}
setInterval(carousel,1000);
img {
width: 100px;
margin-left: 10px;
transition: .2s;
}
.active {
transform: scale(1.1);
}
<div class="container">
<img src="https://i.stack.imgur.com/cb20A.png" class="active"/>
<img src="https://i.stack.imgur.com/cb20A.png"/>
<img src="https://i.stack.imgur.com/cb20A.png"/>
<img src="https://i.stack.imgur.com/cb20A.png"/>
</div>
You can then replace the .active class by whatever you want.

Changing Iframes HTML

I need a script to change the iframes src every certain amount of seconds. The time between the change is different between each one.
Example:
Page Loads
Google.com is loaded.
15 seconds later
Yahoo.com is loaded.
37 seconds later
Ask.com is loaded.
12 seconds later
Dogpile.com is loaded.
and so on and so forth.
I've tried that:
<html>
<head>
<meta charset="utf-8" />
<title>Monitor PresidĂȘncia</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/1.11.8/semantic.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/1.11.8/semantic.min.js"></script>
</head>
<body>
<div style="width: 100%; display: flex;">
<div class="ui teal progress" data-percent="0" id="example1" style="width: 90%;margin-bottom: 0px">
<div class="bar"></div>
</div>
<div class="ui icon buttons" style="width: 10%">
<button class="ui button" style="width: 25%" onclick="menos_um()">
<i class="left chevron icon"></i>
</button>
<button class="ui button " style="width: 25%" onclick="inicia()">
<i class="play icon"></i>
</button>
<button class="ui button" style="width: 25%" onclick="para_aplicacao()">
<i class="pause icon"></i>
</button>
<button class="ui button" style="width: 25%" onclick="mais_um()">
<i class="right chevron icon"></i>
</button>
</div>
</div>
<iframe id="envase" class="frame_mon" style="width: 100%;height: 100%;" src="www.google.com.br"></iframe>
<iframe id="frete_hl" class="frame_mon" style="width: 100%;height: 100%;display: none;" src="www.yahoo.com.br"></iframe>
<iframe id="frete_hl_acum" class="frame_mon" style="width: 100%;height: 100%;display: none;" src="www.terra.com.br"></iframe>
</body>
<script>
var arr_monitores = ["envase", "frete_hl", "frete_hl_acum"];
var num_monitor = 0;
var progresso = 0;
var myVar;
var setintervalatualizaframe;
function mais_um() {
/* if (num_monitor === 2) {
num_monitor = 0;
} else {
num_monitor++;
}
$('.frame_mon').css('display', 'none');
document.getElementById(arr_monitores[num_monitor]).style.display = "";*/
progresso = 100;
myStopFunction();
inicia();
/* if (num_monitor === 2) {
num_monitor = 0;
} else {
num_monitor++;
}*/
};
function menos_um() {
//progresso = 100;
if (num_monitor === 0) {
num_monitor = 2;
} else {
num_monitor--;
}
$('.frame_mon').css('display', 'none');
document.getElementById(arr_monitores[num_monitor]).style.display = "";
progresso = 0;
myStopFunction();
inicia();
};
function inicia() {
clearInterval(setintervalatualizaframe);
myStopFunction();
myVar = setInterval(function () {
if (progresso === 100) {
progresso = 0;
if (num_monitor === 2) {
location.reload();
//num_monitor = 0;
} else {
num_monitor++;
}
$('.frame_mon').css('display', 'none')
document.getElementById(arr_monitores[num_monitor]).style.display = "";
};
progresso++;
progresso++;
$('#example1').data('percent', progresso);
$('#example1').progress();
}, 3800);
}
function myStopFunction() {
clearInterval(myVar);
//atualiza_frame();
}
inicia();
function para_aplicacao(){
clearInterval(myVar);
atualiza_frame();
}
function atualiza_frame() {
clearInterval(setintervalatualizaframe);
setintervalatualizaframe = setInterval(function () {
document.getElementById(arr_monitores[num_monitor]).src=document.getElementById(arr_monitores[num_monitor]).src;
},1);
}
</script>
</html>
The way you are using setInterval and setTimeout is not properly
handled, as it creates a timer id to schedule execution. 0
A much more efficient way is to use the Promises async library, which is displayed below. 1
For websites that won't work, they are using a response header that won't allow their pages to be framed. You can work around this with some back-end program, where the server loads the web files then forwards them. 2
<!DOCTYPE html>
<html>
<head>
<title> Hello </title>
<style>
iframe {
display: block;
width: 1000px;
height: 500px;
margin-left: auto;
margin-right: auto;
}
iframe:focus {
outline: none;
}
button {
display: block;
margin: auto auto;
}
label {
display: block;
margin-left: auto;
margin-right: auto;
}
input {
display: block;
margin: auto auto;
}
</style>
</head>
<body>
<div id='main'>
<button id='wait' onclick='wait()'>Wait</button>
<label>Seconds</label>
<input type='number' id='seconds' placeholder='milliseconds'>
<button id='switching' onclick='webSwitch()'>Switch sites</button>
<iframe id='switchMe' src='https://codepen.io'></iframe>
</div>
<script>
//Array of webpages
var webList = ["https://www.bing.com", "https://www.walmart.com","https://www.codepen.io"];
//For tracking position in array
var count = 0;
//Function to be ran by event
function webSwitch() {
console.log('I have been called');
if (count >= webList.length) {
count = 0;
}
//Setting new URL
document.getElementById('switchMe').src = webList[count];
//Make sure to use next URL
count++;
}
function wait() {
console.log('Click!');
var numMS = document.getElementById('seconds').value;
sleep(numMS).then(() => {
webSwitch();
})
}
function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
</script>
</body>
</html>

Fruit ninja type game in javascript

I'm trying to make a ninja fruit style game in javascript but problems are happening. I have this if statements that compare the variable "fruit" with the index of the "fruits" array. The problem is when I "eliminate" a fruit the other if statements doenst work.
That's how the game needs to work:
1 You start the game, a random name of a fruit appears for you to click on.
2 You click in the image of the fruit and it disappears, in this click another random fruit is generated.
3 An then you finish the game, that's prety much this.
So it's kind hard to explain, but its the same logic as the ninja fruit game. And I dont know if I need to use the shift function to eliminate the fruits in the array as well.
var fruits = ['Banana', 'Apple', 'Pineapple'];
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
if (fruit == fruits[0]) {
bana.onclick = function() {
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
bana.style.display = "none";
}
}
if (fruit == fruits[1]) {
app.onclick = function() {
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
app.style.display = "none";
}
}
if (fruit == fruits[2]) {
pin.onclick = function() {
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
pin.style.display = "none";
}
}
function movFruit() {
document.getElementById("info").style.display = "table";
document.getElementById("fruitAnimation").style.display = "table";
document.getElementById("insructions").style.display = "none";
var elem = document.getElementById("fruitAnimation");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
}
}
}
#fruitAnimation {
position: relative;
display: none;
margin: 0 auto;
}
.fr {
float: left;
padding: 80px;
}
#info {
display: none;
margin: 0 auto;
}
#insructions {
display: table;
margin: 0 auto;
margin-top: 200px;
border: 1px solid black;
padding: 10px;
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<title>JSfruit</title>
</head>
<body>
<div id="info">
<h1>Fruit: <span id="frut"></span></h1>
</div>
<button onclick="movFruit() " style="display: table; margin: 0 auto;"><h4>Start the game</h4></button>
<div id="fruitAnimation">
<div class="fr" id="bana">
<img src="https://orig00.deviantart.net/5c87/f/2016/322/8/9/banana_pixel_art_by_fireprouf-daosk9z.png" width="60" height="60">
</div>
<div class="fr" id="app">
<img src="https://art.ngfiles.com/images/404000/404664_thexxxreaper_pixel-apple.png?f1454891997" width="60" height="60">
</div>
<div class="fr" id="pin">
<img src="https://i.pinimg.com/originals/c2/f9/e9/c2f9e9f8d332da97a836513de98f7b29.jpg" width="60" height="60">
</div>
</div>
<span id="insructions">Click in the fruits and erase them!</span>
</body>
</html>
Right now, you're only attaching handlers to the fruit images at the top level, in your if statements - but once those statements run and the main block finishes, it doesn't get run again.
You should attach handlers to all fruit images at once in the beginning, and then in the handlers, check to see the clicked fruit was valid.
If you're assigning text to an element, assign to textContent, not innerHTML; textContent is quicker, safer, and more predictable.
const fruits = ['Banana', 'Apple', 'Pineapple'];
const getRandomFruit = () => {
const randomIndex = Math.floor(Math.random() * fruits.length);
const fruit = fruits[randomIndex];
document.getElementById("frut").textContent = fruit;
fruits.splice(randomIndex, 1);
return fruit;
};
let fruitToClickOn = getRandomFruit();
bana.onclick = function() {
if (fruitToClickOn !== 'Banana') return;
bana.style.display = "none";
fruitToClickOn = getRandomFruit();
}
app.onclick = function() {
if (fruitToClickOn !== 'Apple') return;
app.style.display = "none";
fruitToClickOn = getRandomFruit();
}
pin.onclick = function() {
if (fruitToClickOn !== 'Pineapple') return;
pin.style.display = "none";
fruitToClickOn = getRandomFruit();
}
function movFruit() {
document.getElementById("info").style.display = "table";
document.getElementById("fruitAnimation").style.display = "table";
document.getElementById("insructions").style.display = "none";
var elem = document.getElementById("fruitAnimation");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
}
}
}
#fruitAnimation {
position: relative;
display: none;
margin: 0 auto;
}
.fr {
float: left;
padding: 80px;
}
#info {
display: none;
margin: 0 auto;
}
#insructions {
display: table;
margin: 0 auto;
margin-top: 200px;
border: 1px solid black;
padding: 10px;
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<title>JSfruit</title>
</head>
<body>
<div id="info">
<h1>Fruit: <span id="frut"></span></h1>
</div>
<button onclick="movFruit() " style="display: table; margin: 0 auto;"><h4>Start the game</h4></button>
<div id="fruitAnimation">
<div class="fr" id="bana">
<img src="https://orig00.deviantart.net/5c87/f/2016/322/8/9/banana_pixel_art_by_fireprouf-daosk9z.png" width="60" height="60">
</div>
<div class="fr" id="app">
<img src="https://art.ngfiles.com/images/404000/404664_thexxxreaper_pixel-apple.png?f1454891997" width="60" height="60">
</div>
<div class="fr" id="pin">
<img src="https://i.pinimg.com/originals/c2/f9/e9/c2f9e9f8d332da97a836513de98f7b29.jpg" width="60" height="60">
</div>
</div>
<span id="insructions">Click in the fruits and erase them!</span>
</body>
</html>

Categories