Javascript/JQuery Math.random to onclick fade to - javascript

I am making a simple game for my school project and the basic Idea is when you press a button to start the game random images will fade in and you have to click as many of them as you can in 30 seconds. I am using Math.random and Javascript for if statements and JQuery for its built in onclick and fadeTo. The function is not working however and I dont know why.Here is my html
<!DOCTYPE html>
<html>
<head>
<title>My test game</title>
<!-- CSS -->
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>Click as many as you can in 30 seconds</h1>
<input id="clickMe" type="button" value="clickme"onclick="randomNumFunc();" />
<!-- Game Area -->
<div id="game-area">
<div id="circle1"></div>
</div>
<!-- Javascript/Jquery -->
<script src="js/JQuery.js"></script>
<script src="js/script.js"></script>
</body>
CSS:
body {
background-color: #CEF6F5;
}
#game-area {
border: 5px solid black;
height: 500px;
background-color: white;
}
#circle1 {
-moz-border-radius: 50px/50px;
-webkit-border-radius: 50px 50px;
border-radius: 50px/50px;
border: solid 21px #f00;
width: 50px;
height: 50px;
opacity: 0.5;
}
and Javascript/Jquery:
/* RNG variable */
var randomNum = Math.floor((Math.random() * 3) + 1);
/* Picture Assignments */
var pic1 = 1;
var pic2 = 2;
var pic3 = 3;
/* RNG Code */
function randomNumFunc() {
document.getElementById('#circle1').innerHTML;
if (randomNum == 1) {
$(document).ready(function() {
$(document).fadeTo('fast', 1);
});
$(document).onclick(function() {
$(document).fadeTo('fast', 0);
});
}
}

Your <input> element should be,
<input id="clickMe" type="button" value="clickme"/>
And the javaScript/jQuery code look like,
$(document).ready(function() {
var randomNum = Math.floor((Math.random() * 3) + 1);
$('#clickMe').click(function(){
if(randomNum == 1){
$('#circle1').fadeTo('fast', 1);
}
else{
$('#circle1').fadeTo('fast', 0);
}
})
});

I think that this is what you want:
script.js:
$(document).ready(function() {
var pic1 = 1;
var pic2 = 2;
var pic3 = 3;
var randomNum = Math.floor((Math.random() * 3) + 1); //every time you click it, will be generate a new randonNum
console.log(randoNum); //It will show in console the number
$('#clickMe').click(function() {
if (randomNum == 1) {
$('#circle1').fadeIn('fast');
} else {
$('#circle1').fadeOut('fast');
}
});
});
and you can remove the onClick method in the input:
<input id="clickMe" type="button" value="clickme" />

Related

Sequential animations on HTML element

guys. I'm trying to create a group of sequential "animations" through css classes on my buttons, but i keep getting a problem where all my buttons receive the effect on the same time and not one after another.
The function playAllSequence should hightlight each button one after another following the sequence present in an array.
I've already tried to put the setTimeOut function inside a closure and tried changed my declaration to let instead of var.
What am i missing?
Thanks in advance
// Get number of buttons on the document
var numberOfButtons = document.querySelectorAll(".btn").length;
var collectionButtonsClicked = [];
var collectionOfRandomColors = [];
var buttonsColors = ["blue", "green", "red", "yellow"];
var gameTitle = document.querySelector("#level-title");
// detecting clicks on the buttons
for ( let i = 0; i < numberOfButtons; i++) {
document.querySelectorAll(".btn")[i].addEventListener("click", function () {
collectionButtonsClicked.push(this.id);
// call click animation function
clickAnimation ();
// Only checks when arrays have the same length so the user have to click all the sequence again
if (collectionButtonsClicked.length === collectionOfRandomColors.length) {
checkClick();
}
})};
// detecting button press to start the game
document.addEventListener("keydown", function (event) {
if (event.key === "a") {
gameTitle.innerHTML = "Game Started";
generateRandomColor();
playAllSequence();
}
});
// check if the click is correct
function checkClick () {
// if correct - Generate new color, disable buttons and play the sequence on all buttons
let arrayRandomStringfied = JSON.stringify(collectionOfRandomColors);
let arrayClickedStringfied = JSON.stringify(collectionButtonsClicked);
if (arrayRandomStringfied === arrayClickedStringfied) {
generateRandomColor();
playAllSequence();
console.log("acertou!")
// erasing click array so the player has to click all the color again
collectionButtonsClicked = [];
} else {
//call fail animation function
failAnimation();
// function to reset the arrays and the title
restartGame();
console.log("errou!")
}
}
//Generate random color and return array - User will have to follow this colors
function generateRandomColor () {
let randomIndex = Math.floor(Math.random() * 4);
collectionOfRandomColors.push(buttonsColors[randomIndex]);
return collectionOfRandomColors;
}
function playAllSequence () {
// disabling all buttons
for ( let i = 0; i < numberOfButtons; i++) {
document.querySelectorAll(".btn")[i].disabled = true;
}
for ( let i = 0; i < collectionOfRandomColors.length; i++ ) {
doSetTimeOut(i);
}
// Enabling all buttons again
for ( let i = 0; i < numberOfButtons; i++) {
document.querySelectorAll(".btn")[i].disabled = false;
}
}
function doSetTimeOut (i) {
let activeButton = document.querySelector("." + collectionOfRandomColors[i]);
// Add pressed effect
activeButton.classList.add("pressed");
// Remove pressed effect after 1 second
setTimeout(function() {
activeButton.classList.remove("pressed")
}, 1000);
}
function clickAnimation () {
}
function failAnimation () {
}
function restartGame () {
collectionOfRandomColors = [];
collectionButtonsClicked = [];
gameTitle.innerHTML = "Press A key to Start";
}
body {
text-align: center;
background-color: #011F3F;
}
#level-title {
font-family: 'Press Start 2P', cursive;
font-size: 3rem;
margin: 5%;
color: #FEF2BF;
}
.container {
display: block;
width: 50%;
margin: auto;
}
.btn {
margin: 25px;
display: inline-block;
height: 200px;
width: 200px;
border: 10px solid black;
border-radius: 20%;
}
.game-over {
background-color: red;
opacity: 0.8;
}
.red {
background-color: red;
}
.green {
background-color: green;
}
.blue {
background-color: blue;
}
.yellow {
background-color: yellow;
}
.pressed {
box-shadow: 0 0 20px white;
background-color: grey;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Simon</title>
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Press+Start+2P" rel="stylesheet">
</head>
<body>
<h1 id="level-title">Press A Key to Start</h1>
<div class="container">
<div class="row">
<div type="button" id="green" class="btn green">
</div>
<div type="button" id="red" class="btn red">
</div>
</div>
<div class="row">
<div type="button" id="yellow" class="btn yellow">
</div>
<div type="button" id="blue" class="btn blue">
</div>
</div>
</div>
<script src="index.js" charset="utf-8"></script>
</body>
</html>
Well, I don't see your sample code to animate even the first button.
If you need independent separate events to happen '1 by 1' visually, you might use a i*1000 as a setTimeout second argument.
If not, here's the code doing something close to what you want to achieve, i believe. Define a function that sets the props you need (box-shadow in this example) for an element taken by index, and sets timeout for a function that will remove the props and call the first function again with the next index:
function animateBtnsSequence( i ){
var btns = document.querySelectorAll(".btn");
btns[i].style.boxShadow = '0 0 20px 1px white';
window.setTimeout(function(){
btns[i].style.boxShadow = '';
if( btns[i+1] )
animateBtnsSequence( i + 1 );
}, 1000)
}
function playAllSequence () {
animateBtnsSequence( 0 );
}

Need help making an image appear on click

I am making a thing where when you click on the hidden image it appears. Every time that I do it, though, the image just stays hidden. I know that I am actually clicking the image because I made it so that it follows under my cursor. It also works in reverse. If the image is visible and I click on it it turns invisible.
Here is my HTML:
document.addEventListener('mousemove', function(e) {
let body = document.querySelector('body');
let boom = document.getElementById('boom');
let left = e.pageX;
let top = e.pageY;
boom.style.left = left + 'px';
boom.style.top = top + 'px';
});
function animation(){
var boom = document.getElementById("boom");
boom.style.display = "none";
document.getElementById("boom").src = "file:///C:/Users/domin/Desktop/Atom/rootfolder/Boom%20Salamon/Salamon.png";
}
body {
background-color: #000000;
}
header {
background: grey;
padding: 10px;
margin: 0px;
font-size: 13px
}
#boom{
display: block;
position: absolute;
transform: translate(-50%,-50%);
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
<title>Boom! Salamon</title>
</head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<header>
<h2 style="color: white; text-align: center">Boom! Salamon.<br>Click in the area below to witness the magic!</h2>
</header>
<img onclick='animation()' id="boom" src='file:///C:/Users/domin/Desktop/Atom/rootfolder/Boom%20Salamon/Boom!.png' height="250" width="250"></img>
<script src="app.js"></script>
</body>
</html>
What's happening?
yes as #Abin mentioned you have not added any code to unhide it I have modified your
html and js file to add this functionality like when you click on text it will be visible again.
Note: i have added that visible condition on click of header text but you can define it anywhere.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="Styles.css">
<title>Boom! Salamon</title>
</head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<header>
<h2 id='clickme' style="color: white; text-align: center">Boom! Salamon.<br>Click here to witness the magic!</h2>
</header>
<img onclick='animation()' id="boom" src='file:///C:/Users/domin/Desktop/Atom/rootfolder/Boom%20Salamon/Boom!.png' height="250" width="250"></img>
<script src="app.js"></script>
</body>
</html>
app.js
document.addEventListener('mousemove', function(e) {
let body = document.querySelector('body');
let boom = document.getElementById('boom');
let left = e.pageX;
let top = e.pageY;
boom.style.left = left + 'px';
boom.style.top = top + 'px';
});
function animation(){
var boom = document.getElementById("boom");
boom.style.visibility = 'hidden';
document.getElementById("boom").src = 'file:///C:/Users/domin/Desktop/Atom/rootfolder/Boom%20Salamon/Salamon.png';
}
document.getElementById("clickme").onclick = function() {
boom.style.visibility = 'visible';
}
in above i have used pure js.
There was nothing in the code you have provided to unhide the image, I have added a sample code that works as per your req. Click on the text, and the image will appear on the bottom.
/* document.addEventListener('mousemove', function(e) {
let body = document.querySelector('body');
let boom = document.getElementById('boom');
let left = e.pageX;
let top = e.pageY;
boom.style.left = left + 'px';
boom.style.top = top + 'px';
});
*/
var clickEl = document.getElementById('click-el')
clickEl.addEventListener('click', function(){
var imgEl = document.getElementById('boom');
imgEl.style.display = 'block';
})
/*
function animation(){
var boom = document.getElementById("boom");
boom.style.display = "none";
document.getElementById("boom").src = "file:///C:/Users/domin/Desktop/Atom/rootfolder/Boom%20Salamon/Salamon.png";
} */
body {
background-color: #000000;
}
header {
background: grey;
padding: 10px;
margin: 0px;
font-size: 13px
}
#boom{
display: none;
}
<header>
<h2 id='click-el' style="color: white; text-align: center">Boom! Salamon.<br>Click here to witness the magic!</h2>
</header>
<img onclick='animation()' id="boom" src='https://static.remove.bg/sample-gallery/graphics/bird-thumbnail.jpg' height="250" width="250"/>

Move an element back and forth diagonally using Java Script

I'm trying to make my div element move back and forth inside a container infinitely.
The goal is to use Java Script only, no CSS animations, jQuery, etc.
const container = document.getElementById('container');
const box = document.getElementById('box');
let t = setInterval(move, 1);
let pos = 1;
function move() {
box.style.left = pos + 'px';
box.style.top = pos + 'px';
pos++;
if (pos === 150) {
clearInterval(t)
}
}
#container{
width: 200px;
height: 200px;
background-color: green;
position: relative;
}
#box{
width: 50px;
height: 50px;
background-color: red;
position: absolute;
animation-direction: alternate;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Animation</title>
<link href="animation.css" rel="stylesheet">
<script defer src="animation.js"></script>
</head>
<body>
<div id="container">
<div id="box"></div>
</div>
</body>
</html>
So here the code. As you see, I've used position relative/absolute to make the element move with setInterval function. But when I try to reverse it back to "it's corner", it just won't work. To be honest, I've tried some stuff already, but I really can't find the solution of doing it without using any other instruments.
Thanks in advance.
You need to increase/decrease the values considering a boolean variable like below:
const container = document.getElementById('container');
const box = document.getElementById('box');
let t = setInterval(move, 1);
let pos = 1;
let test = true;
function move() {
box.style.left = pos + 'px';
box.style.top = pos + 'px';
if (test)
pos++; /* move down */
else
pos--; /* move up */
/* update the direction when you reach the top or bottom limit*/
if (pos >= 150)
test = false
else if (pos <= 0)
test = true;
}
#container {
width: 200px;
height: 200px;
background-color: green;
position: relative;
}
#box {
width: 50px;
height: 50px;
background-color: red;
position: absolute;
}
<div id="container">
<div id="box"></div>
</div>
An alternative to get the same results
const box = document.getElementById('box');
let jump = 1;
let pos = 0;
window.setInterval(() => {
pos = pos + jump;
if (pos > 150 || pos < 0) {
jump = jump * (-1);
}
box.style.left = pos + 'px';
box.style.top = pos + 'px';
}, 1);
#container{
width: 200px;
height: 200px;
background-color: green;
position: relative;
}
#box{
width: 50px;
height: 50px;
background-color: red;
position: absolute;
animation-direction: alternate;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Animation</title>
<link href="animation.css" rel="stylesheet">
<script defer src="animation.js"></script>
</head>
<body>
<div id="container">
<div id="box"></div>
</div>
</body>
</html>

How can I create multiple progress bars using a for loop?

I've been playing around with the code below and using it to create a progress bar that responds to a certain type of data input. The data I'm using comes in the form of an array but I've noticed that the code only creates one progress bar.
How could I embed this within my for loop so that it creates a separate progress bar for each item in the array?
function move() {
var elem = document.getElementById("myBar");
var width = 0;
var id = setInterval(frame, 2000);
function frame() {
if (width >= 100) {
clearInterval(id);
} else {
width=width + 10;
elem.style.width = width + '%';
elem.innerHTML = ((100 - width)/10) + ' mins';
}
}
}
move();
#myProgress {
width: 80%;
background-color: #ddd;
horizontal-align: center;
}
#myBar {
width: 0%;
height: 30px;
background-color: #4CAF50;
text-align: center;
line-height: 30px;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
</head>
<body>
<div id="myProgress">
<div id="myBar"></div>
</div>
</body>
Here is the link to what I'm working on: My Workspace
Side Note: I've been trying to get the progress bar to be centered on the page with a margin: 200px on either side. The margin attribute in my CSS doesn't seem to be doing this and only applying the margin to the left but not to the right - where am I going wrong with this?
Try this
<html>
<style>
#myProgress {
width: 100%;
background-color: #ddd;
}
.myBar {
width: 10%;
height: 30px;
background-color: #4CAF50;
text-align: center;
line-height: 30px;
color: white;
}
</style>
<body>
<div id="myProgress">
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
var progressbars="";
var i;
for (i = 1; i <=10; i++) {
progressbars+="<div class='myBar' style='width:"+i+"%'"
+ " id='myBar"+i+"px'"
+">"+i+"%"+"</div><br/>";
}
$("#myProgress").html(progressbars);
});
</script>
</html>
Using Javascript Only
Just replace previous script with this
<script>
window.onload=function(){
var progressbars="";
var i;
for (i = 1; i <=10; i++) {
progressbars+="<div class='myBar' style='width:"+i+"%'"
+ " id='myBar"+i+"px'"
+">"+i+"%"+"</div><br/>";
}
document.getElementById("myProgress").innerHTML=progressbars;
}
This will generate
I see that you have included bootstrap 4
In that case you can create progress bars with Bootstrap
var progressbars="";
for (var i = 1; i <=10; i++) {
progressbars+='<div class="progress">'
+'<div class="progress-bar" role="progressbar" style="width: '+i+'%" aria-valuenow="'+i+'" aria-valuemin="0" aria-valuemax="100">'+i+'%</div>'
+'</div>';
}
document.querySelector(".feefo").innerHTML=progressbars;
And it looks a lot nicer :)

Animation without jquery, slide left and right

I am trying to slide a div to the left when I show it and slide it to the right when I hide it, but I don't want to use jQuery. Is there a way to do simple animation and support IE7 and IE8 without using a javascript library?
Here is my show/hide js:
function showHide() {
var Elliot = document.getElementById('Daniel').style.display;
if (Elliot == "block") {
document.getElementById('Daniel').style.display = "none";
} else {
document.getElementById('Daniel').style.display = "block";
};
};
HTML would look like:
click me
<div id="Daniel" style="display:block; width: 300px; height: 50px;">
<!-- some stuff -->
</div>
Below is a function that can get you started:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<style>
#yea {
margin-left: 100px;
height: 100px;
width: 100px;
background: blue;
border: 1px black solid;
}
</style>
</head>
<body>
<div id='yea'></div>
<input type="button" value="Capacity Chart" onclick="animateMe();" >
<script>
function animateLeft(obj, from, to){
if(from >= to){
obj.style.visibility = 'hidden';
return;
}
else {
var box = obj;
box.style.marginLeft = from + "px";
setTimeout(function(){
animateLeft(obj, from + 1, to);
}, 25)
}
}
function animateMe() {
animateLeft(document.getElementById('yea'), 100, 700);
}
</script>
</body>
</html>
https://jsfiddle.net/geh7ewLx/

Categories

Resources