I'm trying to do Simon Game. But audio doesn't work on my chrome browser. What to do? - javascript

The animations work perfectly on shapes. But audio files dont play. What might be the reason?
I added all the html, css, and javascript files for you to see.
It still doesnt let me post it, so i am extending the question. I hope someone can solve this issue. Thank you in advance. I'd be so happy for your help
var buttonColours = ["red","blue","green","yellow"];
var gamePattern = [];
function nextSequence() {
var randomNumber = Math.floor(Math.random()*4); // 0-3
var randomChosenColour = buttonColours[randomNumber];
gamePattern.push(randomChosenColour);
//1. Use jQuery to select the button with the same id as the randomChosenColour
$("#"+randomChosenColour).fadeIn().fadeOut().fadeIn();
var audio = new Audio("sounds/" + randomChosenColour + ".mp3");
audio.play();
}
nextSequence();
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 lass="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="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="game.js"></script>
</body>
</html>

Related

JavaScript animations not working (no button flash) and no audio when button clicked

I am working on an online boot camp project and could not get my code to create the proper animation. When I press one of the colored buttons, it should flash, but nothing happens. I downloaded the solution file and it also does not work.
I also tried adding:
console.log(userClickedPattern);
playSound(userChosenColor);
to the bottom of the:
$("#btn").click(function(){}
but that did not seem to make a difference.
What am I doing wrong?
var buttonColors = ["red", "blue", "green", "Yellow"];
var gamePattern = [];
var userClickedPattern = [];
$("#btn").click(function() {
var userChosenColor = $(this).attr("id");
userClickedPattern.push(userChosenColor);
playSound(userChosenColor);
animatePress(userChosenColor);
});
function nextSequence() {
var randomNumber = Math.floor(Math.random() * 4);
var randomChosenColor = buttonColors[randomNumber];
gamePattern.push(randomChosenColor);
$("#" + randomChosenColor).fadeIn(100).fadeOut(100).fadeIn(100);
playSound(randomChosenColor);
}
function playSound(name) {
var audio = new Audio("sounds/" + name + ".mp3");
audio.play();
}
function animatePress(currentColor) {
$("#" + currentColor).addClass("pressed");
setTimeout(function() {
$("#" + currentColor).removeClass("pressed");
}, 100);
}
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;
}
<!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="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="game.js" charset="utf-8"></script>
</body>
</html>
You forgot to define class pressed also your selector for the buttons was wrong #btn instead of .btn
var buttonColors = ["red", "blue", "green", "Yellow"];
var gamePattern = [];
var userClickedPattern = [];
$(".btn").click(function() {
var userChosenColor = $(this).attr("id");
userClickedPattern.push(userChosenColor);
playSound(userChosenColor);
animatePress(userChosenColor);
});
function nextSequence() {
var randomNumber = Math.floor(Math.random() * 4);
var randomChosenColor = buttonColors[randomNumber];
gamePattern.push(randomChosenColor);
$("#" + randomChosenColor).fadeIn(100).fadeOut(100).fadeIn(100);
playSound(randomChosenColor);
}
function playSound(name) {
var audio = new Audio("sounds/" + name + ".mp3");
audio.play();
}
function animatePress(currentColor) {
$("#" + currentColor).addClass("pressed");
setTimeout(function() {
$("#" + currentColor).removeClass("pressed");
}, 100);
}
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 {
border: 2px solid red;
background: black;
opacity: 0.2;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title>Simon</title>
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Press+Start+2P" rel="stylesheet">
<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>

I tried moving my JS script into a separate js file, but it stopped working once I did. How can I fix it?

I just started learning JS, and im not understanding it that well. I am not that great at coding generally, so apologies for this really barebones and very possibly wrong website, but all I wanted to accomplish at the moment was to change the websites background color when I press the button. When I did it in <script< it worked, but when I moved it into a separate JS file, it stopped working. The error message I get is: SyntaxError: Unexpected token '}'. Expected an opening '{' at the start of a function body.
Could someone please help? Thank you in advance!
function makeRed() {
document.getElementById('temp').style.backgroundColor = 'lightsalmon';
}
let btnRed = document.getElementById = ('btnRed');
btnRed.addEventListener("click", makeRed);
body {
background-color: lightyellow;
text-align: center;
padding: 0;
margin: 0;
}
.temperature {
color: darkgoldenrod;
font-family: Optima, sans-serif;
}
input {
border: none;
border-bottom: 2px solid darkgoldenrod;
background-color: lightyellow;
width: 50px;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
#header {
background: darkgoldenrod;
font-size: 20px;
color: lightyellow;
font-family: Optima, sans-serif;
}
<html>
<head>
<title>Sun tester</title>
<link rel="stylesheet" href="stylesheet.css">
<link rel="icon" href="https://external-content.duckduckgo.com/iu/?u=http%3A%2F%2Fcdn.onlinewebfonts.com%2Fsvg%2Fimg_40038.png&f=1&nofb=1" type="image/x-icon">
</head>
<body>
<div id="header">
<h1 id="h1">Sun Tester</h1>
</div>
<div class="temperature">
<p id="temp2">Temperature:
<input type="number" id="temp"> °C</p>
</div>
<button type="button" id="btn-Red">Click Me!</button>
<script src="script.js"></script>
</body>
</html>
you are assigning both btnRed and the document.getElementById method to a String value 'btnRed' instead of actually running the getElementById method and passing it an argument "btnRed"
so just change the
let btnRed = document.getElementById = ('btnRed'); to
let btnRed = document.getElementById('btnRed');
You need to change the HTML element btn-Red to be btnRed and fix up your JavaScript... try this.
function makeRed() {
let r = document.getElementById('temp')
r.style.backgroundColor = 'lightsalmon';
}
let btnRed = document.getElementById('btnRed');
btnRed.addEventListener("click", makeRed);
body {
background-color: lightyellow;
text-align: center;
padding: 0;
margin: 0;
}
.temperature {
color: darkgoldenrod;
font-family: Optima, sans-serif;
}
input {
border: none;
border-bottom: 2px solid darkgoldenrod;
background-color: lightyellow;
width: 50px;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
#header {
background: darkgoldenrod;
font-size: 20px;
color: lightyellow;
font-family: Optima, sans-serif;
}
<html>
<head>
<title>Sun tester</title>
<link rel="stylesheet" href="stylesheet.css">
<link rel="icon" href="https://external-content.duckduckgo.com/iu/?u=http%3A%2F%2Fcdn.onlinewebfonts.com%2Fsvg%2Fimg_40038.png&f=1&nofb=1" type="image/x-icon">
</head>
<body>
<div id="header">
<h1 id="h1">Sun Tester</h1>
</div>
<div class="temperature">
<p id="temp2">Temperature:
<input type="number" id="temp"> °C</p>
</div>
<button type="button" id="btnRed">Click Me!</button>
<script src="script.js"></script>
</body>
</html>

How can I erase the specific container?

I am trying to make a to-do list by myself and it's going pretty well, but I can't remove the correct div. It always removes the first one in the pile. I am not creating new divs, I am basically cloning a template that I've made and setting the display as none.
let d = document.getElementById('botao')
d.addEventListener('click', addTarefa())
function addTarefa() {
let divtarefa = document.getElementById('TarefaEscondida')
clone = divtarefa.cloneNode(true)
clone.id = 'tarefa'
clone.class = "tarefa"
container.appendChild(clone)
clone.setAttribute('display', 'flex')
clone.setAttribute('class', 'tarefa')
clone.setAttribute('id', 'tarefa')
}
function suma() {
let father = document.getElementById('container')
let son = document.getElementById('tarefa')
let apaga = father.removeChild(son)
}
* {
margin: 0;
box-sizing: border-box;
}
body {
background-color: aqua;
}
header {
text-align: center;
background-color: rgb(255, 208, 0);
}
#container {
display: flex;
background-color: beige;
margin-top: 15px;
margin-left: 15%;
margin-right: 15%;
height: 90vh;
align-items: stretch;
padding-top: 8px;
flex-direction: column;
flex-wrap: nowrap;
gap: 8px;
}
.tarefa {
padding: 5px;
background-color: brown;
margin-left: 8px;
margin-right: 8px;
display: flex;
}
.texto {
border: none;
margin-left: 8px;
background-color: brown;
color: white;
width: 90%;
padding: 8px;
}
::placeholder {
color: white;
opacity: 1;
}
.remove {
float: right;
height: 40px;
width: 40px;
color: #333;
cursor: pointer;
}
#botao {
position: fixed;
background-color: brown;
height: 80px;
width: 80px;
border-radius: 50%;
bottom: .8%;
left: 1.5%;
text-align: center;
color: white;
font-weight: 900;
font-size: 4.5rem;
}
#TarefaEscondida {
padding: 5px;
background-color: brown;
/* margin-top: 8px; */
margin-left: 8px;
margin-right: 8px;
display: none;
}
#TextoEscondido {
border: none;
margin-left: 8px;
background-color: brown;
color: white;
width: 90%;
padding: 8px;
}
<!DOCTYPE html>
<html lang="pt-br">
<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">
<link rel="stylesheet" href="style.css">
<title>My To Do list</title>
</head>
<body>
<header id="header">
<h1>My To do list</h1>
</header>
<main id="container">
<div id="TarefaEscondida">
<input type="button" value="Feito" class="remove" onclick="suma()">
<input type="text" placeholder="Escreva aqui..." id="TextoEscondido">
</div>
<div id='tarefa' class="tarefa">
<input type="button" value="Feito" class="remove" onclick="suma()">
<input type="text" placeholder="Escreva aqui..." class="texto">
</div>
</main>
<div id="botao" onclick="addTarefa()">
<P>+ </P>
</div>
<script src="main.js"></script>
</body>
</html>
You don't need to bother with element IDs. DOM navigation will allow you to find the parent of the clicked element, and remove it:
<main id="container">
<div id="TarefaEscondida">
<input type="button" value="Feito" class="remove" onclick="suma(this)">
<input type="text" placeholder="Escreva aqui..." id="TextoEscondido">
</div>
<div id='tarefa' class="tarefa">
<input type="button" value="Feito" class="remove" onclick="suma(this)">
<input type="text" placeholder="Escreva aqui..." class="texto">
</div>
</main>
(Notice how I've changed the onclick so it passes this element)
And then your remove function can simply locate the parent of the clicked element and remove it.
function suma(element) {
element.parentNode.remove();
}
Also, please note: In your function that adds a new element, you should be aware of duplicating element IDs. That will create invalid HTML because IDs must be unique.
Here is a Fiddle example.
let d = document.getElementById('botao')
d.addEventListener('click', addTarefa())
function addTarefa() {
let divtarefa = document.getElementById('TarefaEscondida')
clone = divtarefa.cloneNode(true)
clone.id = 'tarefa'
clone.class = "tarefa"
container.appendChild(clone)
clone.setAttribute('display', 'flex')
clone.setAttribute('class', 'tarefa')
clone.setAttribute('id', 'tarefa')
}
function suma(element) {
element.parentNode.remove();
}
<main id="container">
<div id="TarefaEscondida">
<input type="button" value="Feito" class="remove" onclick="suma(this)">
<input type="text" placeholder="Escreva aqui..." id="TextoEscondido">
</div>
<div id='tarefa' class="tarefa">
<input type="button" value="Feito" class="remove" onclick="suma(this)">
<input type="text" placeholder="Escreva aqui..." class="texto">
</div>
</main>
<div id="botao" onclick="addTarefa()">
<P>+ </P>
</div>
In .addEventListener you put function but don't call it.
d.addEventListener('click',addTarefa)

How to disable and enable a tag click

On clicking the "minus" span the value in "count" input decreases, but it should stop decreasing when it reaches 0. So I disable "minus" span but it remains disabled when value is positive again.
$(document).on('click','.plus',function(){
$(this).closest('.content').find('.count').val(parseInt($(this).closest('.content').find('.count').val()) + 1 );
});
$(document).on('click','.minus',function(){ $(this).closest('.content').find('.count').val(parseInt($(this).closest('.content').find('.count').val()) - 1 );
if ($(this).closest('.content').find('.count').val() == 0) {
$(this).closest('.content').find('.count').val(0);
$(this).closest('.minus').prop('disabled', true);
}else{
$(this).closest('.minus').prop('disabled', false);
}
});
.qty .count {
border: 1px solid #e1ecfb;
color: #000;
display: inline-block;
vertical-align: top;
font-size: 15px;
font-weight: 450;
padding: 0 0;
width: 35px;
text-align: center;
}
.qty .plus {
cursor: pointer;
display: inline-block;
vertical-align: top;
color: white;
background-color: #cee0f9;
width: 25px;
height: 25px;
font: 25px/1 Arial,sans-serif;
text-align: center;
border-radius: 30%;
}
.qty .minus {
cursor: pointer;
display: inline-block;
vertical-align: top;
color: #ffffff;
background-color: #cee0f9;
width: 25px;
height: 25px;
font: 23px/1 Arial,sans-serif;
text-align: center;
border-radius: 30%;
background-clip: padding-box;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
<title>Document</title>
</head>
<body>
<div class="produk_list">
<div class="container-fluid" style="padding-bottom:50px;">
<div class="row data_produk" id="data_produk" style="text-align: center;">
<div class="col-6 gallery" value="1">
<div class="content">
<img src="https://awsimages.detik.net.id/community/media/visual/2021/04/06/sandwich-keju-tomat-dan-alpukat-1_43.jpeg?w=700&q=90" width="150" height="150">
<h6>Product Name</h6>
<h6>Product Price</h6>
<div class="qty" id="qty">
<span class=" btn-primary minus b-dark">-</span>
<input type="number" class="count" name="qty" value="1">
<span class="plus b-dark">+</span>
</div>
<button class="buy-1 btn-button" id="pesan"><i class="fas fa-cart-plus"></i></button>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>
The problem is that else is never reached since when it's 0 it's now disabled and won't be clicked again.
Try this:
$(document).on('click','.plus',function(){
let countField=$(this).siblings('.count');
let iniVal=parseInt(countField.val());
iniVal++;
countField.val(iniVal);
$(this).siblings('.minus').prop('disabled', false);
});
$(document).on('click','.minus',function(){
let countField=$(this).siblings('.count');
let iniVal=parseInt(countField.val());
iniVal--;
countField.val(iniVal);
if(iniVal===0){
$(this).prop('disabled', true);
}
});
or you can avoid using .prop():
$(document).on('click','.plus',function(){
let countField=$(this).siblings('.count');
let iniVal=parseInt(countField.val());
iniVal++;
countField.val(iniVal);
});
$(document).on('click','.minus',function(){
let countField=$(this).siblings('.count');
let iniVal=parseInt(countField.val());
if(iniVal>0){
iniVal--;
countField.val(iniVal);
}
});
Try the below code it works fine.
$(document).on('click','.plus',function(){
var currVal = parseInt($('.count').val()) + parseInt(1);
$('.count').val(currVal);
$('.minus').prop('disabled', false);
});
$(document).on('click','.minus',function(){
var currVal = parseInt($('.count').val()) - parseInt(1);
$('.minus').prop('disabled', false);
if(currVal == 0){
$('.minus').prop('disabled', true);
}
$('.count').val(currVal);
});

Max-height Transitions happening in the wrong order

LTLFTP here.
I finally have a problem seemingly only you can solve. I'm trying to create an accordion style menu and I would like a transition effect. The problem is, whenever I change the max-height property, the transitions happen in the wrong order, the transition durations are not the same, and a mysterious delay shows up.
Any insight into this little problem would be wonderful. Thanks in advance. Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="css\default.css">
<style>
.content {
margin-top: 50px;
width: 1024px;
margin-left: auto;
margin-right: auto;
background-color: #fefefe;
border: 1px solid #888;
padding: 1em;
}
.title {
text-align: center;
}
.dresser {
border: 1px solid #888;
padding: auto 1em;
}
.dresser h2 {
margin: 0px;
padding: 2px;
background-color: #888;
color: #fefefe;
cursor: pointer;
}
.drawer {
padding: 0em 1em;
overflow-y: hidden;
max-height: 0px;
transition-property: max-height;
transition-duration: 2s;
}
</style>
</head>
<body onload="enableDresser();">
<div class="content">
<div class="title">
<h1>Dashboard</h1>
</div>
<div class="dresser">
<h2 class="drawerLabel"> <span>▸</span> Contact</h2>
<div class="drawer">
<h1>Stuff</h1>
</div>
<h2 class="drawerLabel"> <span>▸</span> Links</h2>
<div class="drawer">
<h1>Stuff</h1>
</div>
<h2 class="drawerLabel"> <span>▸</span> Documents</h2>
<div class="drawer">
<h1>Stuff</h1>
</div>
<!-- <h2 class="drawerLabel"> <span>▸</span> Guides</h2>
<div class="drawer">
<h1>Stuff</h1>
</div>-->
</div>
</div>
<script type="text/javascript">
var drawerLabels = document.getElementsByClassName("drawerLabel");
//console.log(drawerLabels);
function enableDresser() {
for (var i = 0; i < drawerLabels.length; i++) {
drawerLabels[i].onclick = function() {
openDrawer(this);
}
}
openDrawer(drawerLabels[1]);
}
function closeDresser() {
for (i=0; i<drawerLabels.length; i++) {
drawerLabels[i].firstElementChild.innerHTML = "▸";
drawerLabels[i].nextElementSibling.style.maxHeight = "0px";
}
}
function openDrawer(labelElement) {
closeDresser();
labelElement.firstElementChild.innerHTML = "▾";
labelElement.nextElementSibling.style.maxHeight = "1000px";
}
</script>
</body>
</html>

Categories

Resources