html css js button onclick removing and adding class - javascript

I know there are a lot of question similar but none have helped me so I'm here.
I have a 9 button grid, if i click one it change color (orange) but if i click another one they both stay orange. i don't want it. i want that if a button is already orange, the new one get colored but the first one return to normal color. I tried in a lot of ways but i'm not so good at js and HTML so i'm not understanding where the problem is
function hide() {
var x = document.getElementById("demo");
var y = document.getElementById("demo2")
if (x.style.display === "none") {
x.style.display = "inline-flex";
} else {
x.style.display = "inline-flex";
}
if (y.style.display === "inline-flex") {
y.style.display = "none"
}
}
function hide2() {
var x = document.getElementById("demo2");
var y = document.getElementById("demo");
if (x.style.display === "none") {
x.style.display = "inline-flex";
} else {
x.style.display = "inline-flex";
}
if (y.style.display === "inline-flex") {
y.style.display = "none"
}
}
document.getElementById('sel').onclick = function() {
var className = ' ' + sel.className + ' ';
var a = document.getElementById('sel2');
var b = document.getElementById('sel2');
var c = document.getElementById('sel3');
var d = document.getElementById('sel4');
var e = document.getElementById('sel5');
var f = document.getElementById('sel6');
var g = document.getElementById('sel7');
var h = document.getElementById('sel8');
var i = document.getElementById('sel9');
if (~className.indexOf(' btn ')) {
this.className = className.replace(' btn ', 'btn2 ');
this.a = a.replace(' btn2 ', 'btn ')
this.b = b.replace(' btn2 ', 'btn ')
this.c = c.replace(' btn2 ', 'btn ')
this.d = d.replace(' btn2 ', 'btn ')
this.e = e.replace(' btn2 ', 'btn ')
this.f = f.replace(' btn2 ', 'btn ')
this.g = g.replace(' btn2 ', 'btn ')
this.h = h.replace(' btn2 ', 'btn ')
this.i = i.replace(' btn2 ', 'btn ')
} else {
this.className = className.replace('btn2 ', 'btn ');
}
}
document.getElementById('sel2').onclick = function() {
var className = ' ' + sel2.className + ' ';
if (~className.indexOf(' btn ')) {
this.className = className.replace(' btn ', 'btn2 ');
} else {
this.className = className.replace('btn2 ', 'btn ');
}
}
document.getElementById('sel3').onclick = function() {
var className = ' ' + sel3.className + ' ';
if (~className.indexOf(' btn ')) {
this.className = className.replace(' btn ', 'btn2 ');
} else {
this.className = className.replace('btn2 ', 'btn ');
}
}
document.getElementById('sel4').onclick = function() {
var className = ' ' + sel4.className + ' ';
if (~className.indexOf(' btn ')) {
this.className = className.replace(' btn ', 'btn2 ');
} else {
this.className = className.replace('btn2 ', 'btn ');
}
}
document.getElementById('sel5').onclick = function() {
var className = ' ' + sel5.className + ' ';
if (~className.indexOf(' btn ')) {
this.className = className.replace(' btn ', 'btn2 ');
} else {
this.className = className.replace('btn2 ', 'btn ');
}
}
document.getElementById('sel6').onclick = function() {
var className = ' ' + sel6.className + ' ';
if (~className.indexOf(' btn ')) {
this.className = className.replace(' btn ', 'btn2 ');
} else {
this.className = className.replace('btn2 ', 'btn ');
}
}
document.getElementById('sel7').onclick = function() {
var className = ' ' + sel7.className + ' ';
if (~className.indexOf(' btn ')) {
this.className = className.replace(' btn ', 'btn2 ');
} else {
this.className = className.replace('btn2 ', 'btn ');
}
}
document.getElementById('sel8').onclick = function() {
var className = ' ' + sel8.className + ' ';
if (~className.indexOf(' btn ')) {
this.className = className.replace(' btn ', 'btn2 ');
} else {
this.className = className.replace('btn2 ', 'btn ');
}
}
document.getElementById('sel9').onclick = function() {
var className = ' ' + sel9.className + ' ';
if (~className.indexOf(' btn ')) {
this.className = className.replace(' btn ', 'btn2 ');
} else {
this.className = className.replace('btn2 ', 'btn ');
}
}
body {
font-family: "Open Sans", sans-serif;
background-color: white;
}
.flex-col {
display: flex;
flex-direction: column;
}
.flex-row {
display: flex;
flex-direction: row;
}
.justify {
justify-content: center;
}
.align {
align-items: center;
}
.evenly {
justify-content: space-evenly;
}
.between {
justify-content: space-between;
}
.border {
border: 1px solid black;
}
.m-0 {
margin: 0;
}
.spacer {
display: flex;
flex-direction: column;
flex-grow: 1;
}
.grow {
flex-grow: 1;
}
.orange {
color: orange;
}
.bold {
font-weight: bold;
}
.bg {
background-color: whitesmoke;
}
.tabtitle {
font-weight: bold;
}
.tariffe {
font-size: small;
}
.intro {
text-align: center;
}
.tartitle {
font-size: medium;
}
div h2 {
font-size: xx-large;
}
.cont {
display: block;
position: relative;
padding-left: 35px;
margin-bottom: 12px;
margin-top: 12px;
cursor: pointer;
}
.m-7 {
margin-top: 7px;
}
.m-14 {
margin: 14px;
padding: 0px;
}
div input {
border-radius: 3px;
border: solid 1px black;
}
div input:focus {
outline: none;
}
.richiedi {
text-align: center;
padding: 5px 50px;
}
.tabcosti {
background-color: darkorange;
border: solid darkorange 1px;
}
.border {
border: solid darkorange 1px;
}
.black {
color: black;
}
.white {
color: white;
}
.m-left-50 {
margin-left: 200px;
}
.x-small {
font-size: x-small;
}
.tabcosti2 {
border-top: 0px;
border: solid darkorange 1px;
}
.margin-left {
margin-left: 20px;
}
.info {
width: 215px;
height: 20px;
}
.info2 {
width: 75px;
height: 20px;
margin: 10px;
}
.small {
font-size: small;
}
.unbtn {
border: 0px;
width: 20vw;
height: 30px;
background-color: whitesmoke;
}
.unbtn:focus {
outline: none;
background-color: darkorange;
color: white;
}
.hide {
display: none;
}
.btn {
background-color: whitesmoke;
border-radius: 3px;
border: none;
text-decoration: none;
flex-grow: 1;
margin: 10px;
height: 30px;
}
.btn2 {
background-color: darkorange;
color: white;
border: none;
text-decoration: none;
flex-grow: 1;
margin: 10px;
height: 30px;
}
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="Normalize.css">
<link rel="stylesheet" href="Style.css">
<title>Document</title>
</head>
<body>
<div class="container justify flex-row">
<div class="flex-col">
<div class="justify flex-row">
<h1 class="intro">Vuoi conoscere quali potrebbero <br> essere i <strong>costi</strong> della attività di <span class="orange">logistica</span> e <br>
<span class="orange">trasporto</span> se affidassi i tuoi prodotti a <br> Gruppo Sinergia?</h1>
</div>
<div class="justify flex-row">
<h2 class="orange">Calcola il tuo preventivo!</h2>
</div>
<div class="justify flex-row">
<h3 class="tariffe"> <span class="bold tartitle">Tariffa di Gestione</span>: comprende le tutte le attività di gestione del prodotto, le attività di gestione<br> dell’ordine, le attività di gestione del reso e il trasporto nazionale e internazionale.</h3>
</div>
<div class="justify flex-row">
<h3 class="tariffe"><span class="bold tartitle">Tariffa di Stoccaggio</span>: rappresenta il valore del singolo prodotto per la conservazione presso la<br> struttura di Gruppo Sinergia.</h3>
</div>
<!--^tariffe^-->
<div class="justify flex-row">
<p class="tabtitle">TIPOLOGIA PRODOTTO</p>
</div>
<!--Parte di codice con button-->
<div class="justify evenly flex-row">
<div class="flex-col">
<div class="flex-row">
<button id="sel" class="btn bottoneCategoria">Abbigliamento e Scarpe</button>
</div>
<div class="flex-row">
<button id="sel2" class="btn bottoneCategoria">Pet & Food</button>
</div>
<div class="flex-row">
<button id="sel3" class="btn bottoneCategoria">Sport e Tempo libero</button>
</div>
</div>
<div class="flex-col">
<div class="flex-row">
<button id="sel4" class="btn bottoneCategoria">Elettronica e Informatica</button>
</div>
<div class="flex-row">
<button id="sel5" class="btn bottoneCategoria">Casa e Cucina</button>
</div>
<div class="flex-row">
<button id="sel6" class="btn bottoneCategoria">Auto e Moto</button>
</div>
</div>
<div class="flex-col">
<div class="flex-row">
<button id="sel7" class="btn bottoneCategoria">Food & Beverage</button>
</div>
<div class="flex-row">
<button id="sel8" class="btn bottoneCategoria">Belleza e Salute</button>
</div>
<div class="flex-row">
<button id="sel9" class="btn bottoneCategoria">Altro</button>
</div>
</div>
</div>
<div class="justify flex-row">
<p class="tabtitle">DIMENSIONI PRODOTTO</p>
</div>
<div class="flex-row justify evenly">
<div class="flex-col">
<div class="flex-row">
<button class="unbtn" onclick="hide()">Standard</button>
</div>
</div>
<div class="flex-col">
<div class="flex-row">
<button class="unbtn" onclick="hide2()">Fuori misura</button>
</div>
</div>
</div>
<div id="demo2" class="justify m-30 evenly bg flex-row hide">
<div class="flex-col">
<div class="flex-row">
<p>Inserisci le dimensioni per il singolo prodotto (cm)</p>
</div>
<div class="flex-row justify evenly">
<input class="small info2" type="text" placeholder="lunghezza">
<input class="small info2" type="text" placeholder="larghezza">
<input class="small info2" type="text" placeholder="altezza">
</div>
</div>
</div>
<div id="demo" class="justify m-30 evenly flex-row bg hide">
<div class="flex-col">
<div class="align flex-row">
<input class="cont" type="radio" value="Busta 35x25x3" name="Scatola"> Busta 35x25x3
</div>
<div class="align flex-row">
<input class="cont" type="radio" value="Busta 39x31x5" name="Scatola"> Busta 39x31x5
</div>
<div class="align flex-row">
<input class="cont" type="radio" value="Scatola 27x16x10" name="Scatola"> Scatola 27x16x10
</div>
</div>
<div class="flex-col">
<div class="align flex-row">
<input class="cont" type="radio" value="Scatola 24x15x17" name="Scatola"> Scatola 24x15x17
</div>
<div class="align flex-row">
<input class="cont" type="radio" value="Scatola 37x28x8" name="Scatola"> Scatola 37x28x8
</div>
<div class="align flex-row">
<input class="cont" type="radio" value="Scatola 44x30x9" name="Scatola"> Scatola 44x30x9
</div>
</div>
<div class="flex-col">
<div class="align flex-row">
<input class="cont" type="radio" value="Scatola 61x46x40" name="Scatola"> Scatola 61x46x40
</div>
<div class="align flex-row">
<input class="cont" type="radio" value="Scatola 51x36x12" name="Scatola"> Scatola 51x36x12
</div>
<div class="align flex-row">
<input class="cont" type="radio" value="Scatola 59x38x32" name="Scatola"> Scatola 59x38x32
</div>
</div>
</div>
<div class="flex-row bg m-7 justify evenly">
<div class="flex-col">
<div class="align flex-row">
<input class="cont" type="radio" value="0-1 kg" name="Peso"> 0-1 kg
</div>
<div class="align flex-row">
<input class="cont" type="radio" value="3-5 kg" name="Peso"> 3-5 kg
</div>
</div>
<div class="flex-col">
<div class="align flex-row">
<input class="cont" type="radio" value="1-2 kg" name="Peso"> 1-2 kg
</div>
<div class="align flex-row">
<input class="cont" type="radio" value="5-10 kg" name="Peso"> 5-10 kg
</div>
</div>
<div class="flex-col">
<div class="align flex-row">
<input class="cont" type="radio" value="2-3 kg" name="Peso"> 2-3 kg
</div>
</div>
</div>
<div class="justify evenly flex-row">
<div class="flex-col">
<p>TARIFFA DI GESTIONE</p>
</div>
<div class="flex-col">
<p>TARIFFA DI STOCCAGGIO</p>
</div>
</div>
<div class="tabcosti justify flex-row">
<div class="flex-col">
<p>€ <span class="white">4,56</span></p>
</div>
<div class="flex-col">
<p class="m-left-50">€ <span class="white">0,16</span> <span class="x-small">al mese</span></p>
</div>
</div>
<div class="flex-row tabcosti2">
<div class="flex-col align">
<div class="flex-row">
<p>€ <span class="orange">3,12</span><span> spedizione</span> ITALIA</p>
</div>
<div class="flex-row">
<p>€ <span class="orange">6,70</span><span> spedizione</span> EUROPA</p>
</div>
<div class="flex-row">
<p class="margin-left">€ <span class="orange">6,70</span><span> spedizione</span> WORLDWIDE* ZONA 6</p>
</div>
</div>
<div class="flex-col spacer"></div>
</div>
<div class="flex-row justify intro">
<p class="tariffe">
I valori sono calcolati con una media non superiore ai 10 ordini al giorni.<br> Per progetti con movimentazioni maggiori sono previste tariffe migliorative.<br> Se vuoi una quotazione ad hoc per iltuo modello di business e la tua tipologia<br> di prodotti, contattaci!
</p>
</div>
<div class="justify flex-row bg">
<div class="flex-col">
<div class="flex-row">
<p>Nome e Cognome</p>
</div>
<div class="flex-row">
<p>E-mail</p>
</div>
<div class="flex-row">
<p>Telefono</p>
</div>
</div>
<div class="flex-col">
<div class="flex-row">
<input class="small info m-14" type="text">
</div>
<div class="flex-row">
<input class="small info m-14" type="text">
</div>
<div class="flex-row">
<input class="small info m-14" type="text">
</div>
</div>
</div>
<div class="flex-row m-7 justify">
<button class="richiedi">
Richiedi un preventivo
</button>
</div>
</div>
</div>
</body>
</html>
Just to let everyone know, the function in js i'm trying to make to solve this is just on the first button (ID sel) and i've tried telling the code to replace the colored class with the uncolored one.
I also know that it will look strange cause i have used 2 different ways to create a variable, but i found all the other function i used on stack overflow written like that (i just changed the ID name) but i don't know if there are differences on how i then added the other variables.

You can easily achieve this using the below steps
First, remove all code in your javascript regarding click listener.
Then, store a list of buttons using this
var buttons = document.querySelectorAll('.bottoneCategoria');
Then, add this function. Basically, this function will be called whenever one of your buttons is clicked.
function onButtonClick(event) {
// Get the button on which user clicked using event.target
let clickedButton = event.target;
// Loop over all your buttons and replace the btn2 with btn
// This means all buttons will now be normal
for (let i = 0; i < buttons.length; i++) {
buttons[i].classList.replace('btn2', 'btn');
}
// Finally change your clicked button from btn to btn2
// This will make your clicked button to orange while rest will be normall
clickedButton.classList.replace('btn', 'btn2');
}
Finally, loop over all your buttons and attach the function you created in previous step to all the buttons.
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', onButtonClick);
}
Check the working code snippet for more details.
function hide() {
var x = document.getElementById("demo");
var y = document.getElementById("demo2")
if (x.style.display === "none") {
x.style.display = "inline-flex";
} else {
x.style.display = "inline-flex";
}
if (y.style.display === "inline-flex") {
y.style.display = "none"
}
}
function hide2() {
var x = document.getElementById("demo2");
var y = document.getElementById("demo");
if (x.style.display === "none") {
x.style.display = "inline-flex";
} else {
x.style.display = "inline-flex";
}
if (y.style.display === "inline-flex") {
y.style.display = "none"
}
}
var buttons = document.querySelectorAll('.bottoneCategoria');
function onButtonClick(event) {
let clickedButton = event.target;
for (let i = 0; i < buttons.length; i++) {
buttons[i].classList.replace('btn2', 'btn');
}
clickedButton.classList.replace('btn', 'btn2');
}
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', onButtonClick);
}
body {
font-family: "Open Sans", sans-serif;
background-color: white;
}
.flex-col {
display: flex;
flex-direction: column;
}
.flex-row {
display: flex;
flex-direction: row;
}
.justify {
justify-content: center;
}
.align {
align-items: center;
}
.evenly {
justify-content: space-evenly;
}
.between {
justify-content: space-between;
}
.border {
border: 1px solid black;
}
.m-0 {
margin: 0;
}
.spacer {
display: flex;
flex-direction: column;
flex-grow: 1;
}
.grow {
flex-grow: 1;
}
.orange {
color: orange;
}
.bold {
font-weight: bold;
}
.bg {
background-color: whitesmoke;
}
.tabtitle {
font-weight: bold;
}
.tariffe {
font-size: small;
}
.intro {
text-align: center;
}
.tartitle {
font-size: medium;
}
div h2 {
font-size: xx-large;
}
.cont {
display: block;
position: relative;
padding-left: 35px;
margin-bottom: 12px;
margin-top: 12px;
cursor: pointer;
}
.m-7 {
margin-top: 7px;
}
.m-14 {
margin: 14px;
padding: 0px;
}
div input {
border-radius: 3px;
border: solid 1px black;
}
div input:focus {
outline: none;
}
.richiedi {
text-align: center;
padding: 5px 50px;
}
.tabcosti {
background-color: darkorange;
border: solid darkorange 1px;
}
.border {
border: solid darkorange 1px;
}
.black {
color: black;
}
.white {
color: white;
}
.m-left-50 {
margin-left: 200px;
}
.x-small {
font-size: x-small;
}
.tabcosti2 {
border-top: 0px;
border: solid darkorange 1px;
}
.margin-left {
margin-left: 20px;
}
.info {
width: 215px;
height: 20px;
}
.info2 {
width: 75px;
height: 20px;
margin: 10px;
}
.small {
font-size: small;
}
.unbtn {
border: 0px;
width: 20vw;
height: 30px;
background-color: whitesmoke;
}
.unbtn:focus {
outline: none;
background-color: darkorange;
color: white;
}
.hide {
display: none;
}
.btn {
background-color: whitesmoke;
border-radius: 3px;
border: none;
text-decoration: none;
flex-grow: 1;
margin: 10px;
height: 30px;
}
.btn2 {
background-color: darkorange;
color: white;
border: none;
text-decoration: none;
flex-grow: 1;
margin: 10px;
height: 30px;
}
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="Normalize.css">
<link rel="stylesheet" href="Style.css">
<title>Document</title>
</head>
<body>
<div class="container justify flex-row">
<div class="flex-col">
<div class="justify flex-row">
<h1 class="intro">Vuoi conoscere quali potrebbero <br> essere i <strong>costi</strong> della attività di <span class="orange">logistica</span> e <br>
<span class="orange">trasporto</span> se affidassi i tuoi prodotti a <br> Gruppo Sinergia?</h1>
</div>
<div class="justify flex-row">
<h2 class="orange">Calcola il tuo preventivo!</h2>
</div>
<div class="justify flex-row">
<h3 class="tariffe"> <span class="bold tartitle">Tariffa di Gestione</span>: comprende le tutte le attività di gestione del prodotto, le attività di gestione<br> dell’ordine, le attività di gestione del reso e il trasporto nazionale e internazionale.</h3>
</div>
<div class="justify flex-row">
<h3 class="tariffe"><span class="bold tartitle">Tariffa di Stoccaggio</span>: rappresenta il valore del singolo prodotto per la conservazione presso la<br> struttura di Gruppo Sinergia.</h3>
</div>
<!--^tariffe^-->
<div class="justify flex-row">
<p class="tabtitle">TIPOLOGIA PRODOTTO</p>
</div>
<!--Parte di codice con button-->
<div class="justify evenly flex-row">
<div class="flex-col">
<div class="flex-row">
<button id="sel" class="btn bottoneCategoria">Abbigliamento e Scarpe</button>
</div>
<div class="flex-row">
<button id="sel2" class="btn bottoneCategoria">Pet & Food</button>
</div>
<div class="flex-row">
<button id="sel3" class="btn bottoneCategoria">Sport e Tempo libero</button>
</div>
</div>
<div class="flex-col">
<div class="flex-row">
<button id="sel4" class="btn bottoneCategoria">Elettronica e Informatica</button>
</div>
<div class="flex-row">
<button id="sel5" class="btn bottoneCategoria">Casa e Cucina</button>
</div>
<div class="flex-row">
<button id="sel6" class="btn bottoneCategoria">Auto e Moto</button>
</div>
</div>
<div class="flex-col">
<div class="flex-row">
<button id="sel7" class="btn bottoneCategoria">Food & Beverage</button>
</div>
<div class="flex-row">
<button id="sel8" class="btn bottoneCategoria">Belleza e Salute</button>
</div>
<div class="flex-row">
<button id="sel9" class="btn bottoneCategoria">Altro</button>
</div>
</div>
</div>
<div class="justify flex-row">
<p class="tabtitle">DIMENSIONI PRODOTTO</p>
</div>
<div class="flex-row justify evenly">
<div class="flex-col">
<div class="flex-row">
<button class="unbtn" onclick="hide()">Standard</button>
</div>
</div>
<div class="flex-col">
<div class="flex-row">
<button class="unbtn" onclick="hide2()">Fuori misura</button>
</div>
</div>
</div>
<div id="demo2" class="justify m-30 evenly bg flex-row hide">
<div class="flex-col">
<div class="flex-row">
<p>Inserisci le dimensioni per il singolo prodotto (cm)</p>
</div>
<div class="flex-row justify evenly">
<input class="small info2" type="text" placeholder="lunghezza">
<input class="small info2" type="text" placeholder="larghezza">
<input class="small info2" type="text" placeholder="altezza">
</div>
</div>
</div>
<div id="demo" class="justify m-30 evenly flex-row bg hide">
<div class="flex-col">
<div class="align flex-row">
<input class="cont" type="radio" value="Busta 35x25x3" name="Scatola"> Busta 35x25x3
</div>
<div class="align flex-row">
<input class="cont" type="radio" value="Busta 39x31x5" name="Scatola"> Busta 39x31x5
</div>
<div class="align flex-row">
<input class="cont" type="radio" value="Scatola 27x16x10" name="Scatola"> Scatola 27x16x10
</div>
</div>
<div class="flex-col">
<div class="align flex-row">
<input class="cont" type="radio" value="Scatola 24x15x17" name="Scatola"> Scatola 24x15x17
</div>
<div class="align flex-row">
<input class="cont" type="radio" value="Scatola 37x28x8" name="Scatola"> Scatola 37x28x8
</div>
<div class="align flex-row">
<input class="cont" type="radio" value="Scatola 44x30x9" name="Scatola"> Scatola 44x30x9
</div>
</div>
<div class="flex-col">
<div class="align flex-row">
<input class="cont" type="radio" value="Scatola 61x46x40" name="Scatola"> Scatola 61x46x40
</div>
<div class="align flex-row">
<input class="cont" type="radio" value="Scatola 51x36x12" name="Scatola"> Scatola 51x36x12
</div>
<div class="align flex-row">
<input class="cont" type="radio" value="Scatola 59x38x32" name="Scatola"> Scatola 59x38x32
</div>
</div>
</div>
<div class="flex-row bg m-7 justify evenly">
<div class="flex-col">
<div class="align flex-row">
<input class="cont" type="radio" value="0-1 kg" name="Peso"> 0-1 kg
</div>
<div class="align flex-row">
<input class="cont" type="radio" value="3-5 kg" name="Peso"> 3-5 kg
</div>
</div>
<div class="flex-col">
<div class="align flex-row">
<input class="cont" type="radio" value="1-2 kg" name="Peso"> 1-2 kg
</div>
<div class="align flex-row">
<input class="cont" type="radio" value="5-10 kg" name="Peso"> 5-10 kg
</div>
</div>
<div class="flex-col">
<div class="align flex-row">
<input class="cont" type="radio" value="2-3 kg" name="Peso"> 2-3 kg
</div>
</div>
</div>
<div class="justify evenly flex-row">
<div class="flex-col">
<p>TARIFFA DI GESTIONE</p>
</div>
<div class="flex-col">
<p>TARIFFA DI STOCCAGGIO</p>
</div>
</div>
<div class="tabcosti justify flex-row">
<div class="flex-col">
<p>€ <span class="white">4,56</span></p>
</div>
<div class="flex-col">
<p class="m-left-50">€ <span class="white">0,16</span> <span class="x-small">al mese</span></p>
</div>
</div>
<div class="flex-row tabcosti2">
<div class="flex-col align">
<div class="flex-row">
<p>€ <span class="orange">3,12</span><span> spedizione</span> ITALIA</p>
</div>
<div class="flex-row">
<p>€ <span class="orange">6,70</span><span> spedizione</span> EUROPA</p>
</div>
<div class="flex-row">
<p class="margin-left">€ <span class="orange">6,70</span><span> spedizione</span> WORLDWIDE* ZONA 6</p>
</div>
</div>
<div class="flex-col spacer"></div>
</div>
<div class="flex-row justify intro">
<p class="tariffe">
I valori sono calcolati con una media non superiore ai 10 ordini al giorni.<br> Per progetti con movimentazioni maggiori sono previste tariffe migliorative.<br> Se vuoi una quotazione ad hoc per iltuo modello di business e la tua tipologia<br> di prodotti, contattaci!
</p>
</div>
<div class="justify flex-row bg">
<div class="flex-col">
<div class="flex-row">
<p>Nome e Cognome</p>
</div>
<div class="flex-row">
<p>E-mail</p>
</div>
<div class="flex-row">
<p>Telefono</p>
</div>
</div>
<div class="flex-col">
<div class="flex-row">
<input class="small info m-14" type="text">
</div>
<div class="flex-row">
<input class="small info m-14" type="text">
</div>
<div class="flex-row">
<input class="small info m-14" type="text">
</div>
</div>
</div>
<div class="flex-row m-7 justify">
<button class="richiedi">
Richiedi un preventivo
</button>
</div>
</div>
</div>
<script>
</script>
</body>
</html>

Related

Delete Firebase entries onclick in a button from a insertAdjacentHTML

I am trying to delete some entries in FirebaseDatabase and I am having problems. The console returns the error Uncaught SyntaxError: Invalid or unexpected token only in the first entry, and for the others returns Uncaught ReferenceError: MXcLdklS39mrnk7PQEe is not defined at HTMLButtonElement.onclick.
The code is the following:
const database = firebase.database();
var imagenBanner, count;
div = document.getElementById( 'accordion' );
database.ref(`/marketing/banners`).once('value').then(function (snap) {
count = 1;
snap.forEach(function (childSnapshot) {
console.log(childSnapshot.val().titulo)
var str =`
<div class="card">
<div class="card-header" id="heading${count}">
<h5 class="mb-0">
<button class="btn btn-link" data-toggle="collapse" data-target="#collapse${count}" aria-expanded="true" aria-controls="collapse${count}">
${childSnapshot.val().titulo}
</button>
</h5>
</div>
<div id="collapse${count}" class="collapse show" aria-labelledby="heading${count}" data-parent="#accordion">
<div class="card-body">
Introduce el banner que se mostrara al iniciar la aplicación. Especifique las imágenes y la descripción de la página.
<div style="margin: 20px 50px;">
<div class="input-group mb-3">
<span class="input-group-text" id="basic-addon1">Titulo</span>
<input id="bannerTit${childSnapshot.key}" type="text" class="form-control" placeholder="Titulo" aria-label="Titulo" aria-describedby="Titulo" value="${childSnapshot.val().titulo}">
</div>
<div class="input-group mb-3">
<span class="input-group-text" id="basic-addon1">Descripción</span>
<input id="bannerDes${childSnapshot.key}" type="text" class="form-control" placeholder="Descripción" aria-label="Descripción" aria-describedby="Descripción" value="${childSnapshot.val().descripcion}">
</div>
<div style="width:auto; margin:0 auto; text-align: center;">
<img src="${childSnapshot.val().imagen}" class="d-inline-block align-middle d-lg-none" style="max-width:100%; align-self: center; display: inline-block!important;" alt="">
</div>
<div class="custom-file" style="margin: auto; text-align: center;">
<input type="file" class="form-control" id="inputImage${childSnapshot.key}" accept="image/*">
</div>
<p style="margin: 15px 0px; text-align: end;">
<button class="btn btn-dark" id="guardarButton${childSnapshot.key}" class="btn btn-sm btn-outline-secondary" onclick="saveBanner(${childSnapshot.key})">Guardar Banner</button>
<button class="btn btn-danger" id="eliminarButton${childSnapshot.key}" class="btn btn-sm btn-outline-secondary" onclick="deleteBanner(${childSnapshot.key})">Eliminar Banner</button>
</p>
</div>
</div>
</div>
</div>
`;
div.insertAdjacentHTML( 'beforeend', str );
document.getElementById('inputImage'+childSnapshot.key).addEventListener('change', handleFileSelect, false);
++count;
});
});
var storageRef = firebase.storage().ref();
function handleFileSelect(evt) {
console.log("handleFileSelect(evt)");
evt.stopPropagation();
evt.preventDefault();
file = evt.target.files[0];
metadata = {
'contentType': file.type
};
storageRef.child('banners/' + file.name).put(file, metadata).then(function(snapshot) {
// Let's get a download URL for the file.
snapshot.ref.getDownloadURL().then(function(url) {
imagenBanner = url;
});
}).catch(function(error) {
console.error('Upload failed:', error);
});
}
function deleteBanner(banner) {
console.log(banner);
var result = confirm("Se borrara el banner de marketing. ¿Desea continuar?");
if (result) {
database.ref('/marketing/banners/' + banner).remove();
location.reload();
}
}
function saveBanner(banner) {
console.log(banner);
if (imagenBanner == null){
imagenBanner = "";
}
database.ref('/marketing/banners/' + banner).set({
titulo: document.getElementById("bannerTit"+banner).value,
descripcion: document.getElementById("bannerDes"+banner).value,
imagen: imagenBanner
});
location.reload();
}
function createBanner() {
if (imagenBanner == null){
imagenBanner = "";
}
database.ref('/marketing/banners/').push().set({
titulo: document.getElementById("bannerTitNew").value,
descripcion: document.getElementById("bannerDesNew").value,
imagen: imagenBanner
});
location.reload();
}
function newBanner() {
var str =`
<div class="card">
<div class="card-header" id="headingNew">
<h5 class="mb-0">
<button class="btn btn-link" data-toggle="collapse" data-target="#collapseNew" aria-expanded="true" aria-controls="collapseNew">
Nuevo Banner
</button>
</h5>
</div>
<div id="collapseNew" class="collapse show" aria-labelledby="headingNew" data-parent="#accordion">
<div class="card-body">
Introduce el banner que se mostrara al iniciar la aplicación. Especifique las imágenes y la descripción de la página.
<div style="margin: 20px 50px;">
<div class="input-group mb-3">
<span class="input-group-text" id="basic-addon1">Titulo</span>
<input id="bannerTitNew" type="text" class="form-control" placeholder="Titulo" aria-label="Titulo" aria-describedby="Titulo">
</div>
<div class="input-group mb-3">
<span class="input-group-text" id="basic-addon1">Descripción</span>
<input id="bannerDesNew" type="text" class="form-control" placeholder="Descripción" aria-label="Descripción" aria-describedby="Descripción">
</div>
<div class="custom-file" style="margin: auto; text-align: center;">
<input type="file" class="form-control" id="inputImageNew" accept="image/*">
</div>
<p style="margin: 15px 0px; text-align: end;">
<button class="btn btn-dark" id="guardarButtonNew" class="btn btn-sm btn-outline-secondary" onclick="createBanner()">Guardar Banner</button>
</p>
</div>
</div>
</div>
</div>
`;
div.insertAdjacentHTML( 'afterbegin', str );
document.getElementById('inputImageNew').addEventListener('change', handleFileSelect, false);
}
When I click the delete button from an entry, an alert is supposed to be opened, but nothing happens.
I have checked the ids of the buttons elements and all are correct and exists in the database.
I hope that someone can help me.

Multiple button select scenarios

I have multiple scenarios if a specific buttons is selected. How can I reselect by clicking the button again?
SCENARIOS
(1) training only
(2) travel out NCR only
(3) travel out PH only
(4) training + travel out NCR
(5) training + travel out PH
Here's my code so far
<button class="btn btn-block btn-lg py-3" type="button" onclick="selectReimbursementType()" id="training"
name="training" value="training">
<i class="fas fa-book fa-2x"></i>
<p>Training or Seminar</p>
</button>
<button class="btn btn-block btn-lg py-3" type="button" onclick="selectReimbursementType()"
id="outsideNcr" name="outsideNcr" value="outsideNcr">
<i class="fas fa-bus-alt fa-2x"></i>
<p>Travel outside NCR</p>
</button>
<button class="btn btn-block btn-lg py-3" type="button" onclick="selectReimbursementType()" id="outsidePh"
name="outsidePh" value="outsidePh">
<i class="fas fa-plane-departure fa-2x"></i><br>
<p>Travel outside PH</p>
</button>
<script>
function selectReimbursementType(x) {
var element = document.getElementById(x);
var currentValue = document.getElementById(x).value;
if(currentValue == 'training') {
element.classList.add('is-active');
} else if(currentValue == 'outsideNcr') {
element.classList.add('is-active');
document.getElementById('outsidePh').setAttribute('disabled', true);
} else if(currentValue == 'outsidePh') {
element.classList.add('is-active');
document.getElementById('outsideNcr').setAttribute('disabled', true);
}
}
</script>
https://jsfiddle.net/oy0zh4ws/2/
I used the toggle() and toggleAttribute() methods.
Just use this js code:
function selectReimbursementType(x) {
var element = document.getElementById(x);
var currentValue = document.getElementById(x).value;
var ncr = document.getElementById('outsidePh');
var ph = document.getElementById('outsideNcr');
if(currentValue == 'training') {
element.classList.toggle('is-active');
} else if(currentValue == 'outsideNcr') {
element.classList.toggle('is-active');
ncr.toggleAttribute('disabled');
} else if(currentValue == 'outsidePh') {
element.classList.toggle('is-active');
ph.toggleAttribute('disabled');
}
}
Use element.classList.toggle to toggle class.
Rest disabled state of elements and set again based on condition.
Try it below.
function selectReimbursementType(x) {
var element = document.getElementById(x);
var currentValue = document.getElementById(x).value;
// toggle elements is-active class.
element.classList.toggle('is-active');
// reset disabled
document.getElementById('outsideNcr').removeAttribute('disabled');
document.getElementById('outsidePh').removeAttribute('disabled');
// set disabled button
if (currentValue == 'outsideNcr' && element.classList.contains('is-active')) {
document.getElementById('outsidePh').setAttribute('disabled', true);
}
if (currentValue == 'outsidePh' && element.classList.contains('is-active')) {
document.getElementById('outsideNcr').setAttribute('disabled', true);
}
}
html {
font-size: 14px;
font-family: 'Nunito', sans-serif;
}
.reimbursement-buttons.preview-btn {
margin-top: 20px;
margin-bottom: 5px;
margin-left: auto;
margin-right: auto;
color: #ffffff;
}
.footer {
background: #7f7f7f;
padding: 10px 0px;
}
.reimbursement-card p {
font-size: 12px;
margin-bottom: 0;
}
.reimbursement-card .btn.is-active {
background: #32c5ff;
color: #ffffff;
content: "\f058";
}
.reimbursement-card .btn:hover {
background: #32c5ff;
color: #ffffff;
}
.reimbursement-card .btn:disabled:hover {
background: none;
color: #000000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">
<div class="d-flex justify-content-center form-row">
<div class="p-3">
<div class="card">
<div class="card-body d-flex flex-column align-items-start reimbursement-card p-0">
<button class="btn btn-block btn-lg py-3" type="button" onclick="selectReimbursementType('training')" id="training" name="training" value="training">
<i class="fas fa-book fa-2x"></i>
<p>Training or Seminar</p>
</button>
</div>
</div>
</div>
<div class="p-3">
<div class="card">
<div class="card-body d-flex flex-column align-items-start reimbursement-card p-0">
<button class="btn btn-block btn-lg py-3" type="button" onclick="selectReimbursementType('outsideNcr')" id="outsideNcr" name="outsideNcr" value="outsideNcr">
<i class="fas fa-bus-alt fa-2x"></i>
<p>Travel outside NCR</p>
</button>
</div>
</div>
</div>
<div class="p-3">
<div class="card">
<div class="card-body d-flex flex-column align-items-start reimbursement-card p-0">
<button class="btn btn-block btn-lg py-3" type="button" onclick="selectReimbursementType('outsidePh')" id="outsidePh" name="outsidePh" value="outsidePh">
<i class="fas fa-plane-departure fa-2x"></i><br>
<p>Travel outside PH</p>
</button>
</div>
</div>
</div>
</div>
is-active class has CSS and when a button is clicked then the button gets is-active class. So when the button re-clicked then the button gets same class twice. So easy approach is removing is-active class. As you suggested other below:
SCENARIOS (1) training only (2) travel out NCR only (3) travel out PH only (4) training + travel out NCR (5) training + travel out PH
These SCENARIOS can be reset by removing disabled attribute.
function selectReimbursementType(x) {
var element = document.getElementById(x);
var currentValue = document.getElementById(x).value;
function unSetOption() {
element.classList.remove('is-active')
document.getElementById('outsidePh').removeAttribute('disabled');
document.getElementById('outsideNcr').removeAttribute('disabled');
}
if (element.classList.contains('is-active')) {
unSetOption();
} else if (currentValue == 'training') {
element.classList.add('is-active');
} else if(currentValue == 'outsideNcr') {
element.classList.add('is-active');
document.getElementById('outsidePh').setAttribute('disabled', true);
} else if(currentValue == 'outsidePh') {
element.classList.add('is-active');
document.getElementById('outsideNcr').setAttribute('disabled', true)
}
}
html {
font-size: 14px;
font-family: 'Nunito', sans-serif;
}
.reimbursement-buttons.preview-btn {
margin-top: 20px;
margin-bottom: 5px;
margin-left: auto;
margin-right: auto;
color: #ffffff;
}
.footer {
background: #7f7f7f;
padding: 10px 0px;
}
.reimbursement-card p {
font-size: 12px;
margin-bottom: 0;
}
.reimbursement-card .btn.is-active {
background: #32c5ff;
color: #ffffff;
content: "\f058";
}
.reimbursement-card .btn:hover {
background: #32c5ff;
color: #ffffff;
}
.reimbursement-card .btn:disabled:hover {
background: none;
color: #000000;
}
<div class="d-flex justify-content-center form-row">
<div class="p-3">
<div class="card">
<div class="card-body d-flex flex-column align-items-start reimbursement-card p-0">
<button class="btn btn-block btn-lg py-3" type="button" onclick="selectReimbursementType('training')" id="training" name="training" value="training">
<i class="fas fa-book fa-2x"></i>
<p>Training or Seminar</p>
</button>
</div>
</div>
</div>
<div class="p-3">
<div class="card">
<div class="card-body d-flex flex-column align-items-start reimbursement-card p-0">
<button class="btn btn-block btn-lg py-3" type="button" onclick="selectReimbursementType('outsideNcr')" id="outsideNcr" name="outsideNcr" value="outsideNcr">
<i class="fas fa-bus-alt fa-2x"></i>
<p>Travel outside NCR</p>
</button>
</div>
</div>
</div>
<div class="p-3">
<div class="card">
<div class="card-body d-flex flex-column align-items-start reimbursement-card p-0">
<button class="btn btn-block btn-lg py-3" type="button" onclick="selectReimbursementType('outsidePh')" id="outsidePh" name="outsidePh" value="outsidePh">
<i class="fas fa-plane-departure fa-2x"></i><br>
<p>Travel outside PH</p>
</button>
</div>
</div>
</div>
</div>

Style changing with JS not responding

I am trying to change style to a component by "classList.add" but for some reasons it is working for the first two element and for all the rest is taking the new class.
Is there any reason why this is happening and how I can work around to fix this issue?
Basically a button in the page has opacity: 0.3, by selecting and answer the button will become active from disable and the opacity should be 1
Thanks
Here my example:
for (let i = 0; i < option.length; i++) {
[].forEach.call(opts, (el) => {
el.addEventListener("click", btnClick, false);
});
option[i].addEventListener("click", function() {
// console.log(option[i])
// console.log('CLICKED') // click on answer
move.classList.add("active");
nextSecond.classList.add("active");
nextThird.classList.add("active");
nextFour.classList.add("active");
nextFive.classList.add("active");
nextSix.classList.add("active");
nextSeven.classList.add("active");
});
}
function btnClick() {
[].forEach.call(opts, (el) => {
if (el !== this) el.classList.remove("selected");
});
this.classList.add("selected");
$(".next").removeAttr("disabled");
$(".nextSecond").removeAttr("disabled");
$(".nextThird").removeAttr("disabled");
$(".nextFour").removeAttr("disabled");
$(".nextFive").removeAttr("disabled");
$(".nextSix").removeAttr("disabled");
$(".nextSeven").removeAttr("disabled");
}
.btn {
font-family: 'Noto Sans JP', sans-serif;
font-size: 14px;
line-height: 42px;
align-items: center;
text-align: center;
letter-spacing: 0.05em;
color: #4BA21C;
border: 1px solid black;
width: 220px;
border-radius: 23px;
border: 2px solid #4BA21C;
height: 46px;
background-color: white;
&.btn-left {
margin-left: -56px;
}
&:hover {
cursor: pointer;
}
&.back,
&.next,
&.nextSecond,
&.nextThird.ans.active,
&.nextFour,
&.nextFive,
&.nextSix,
&.nextSeven {
width: 116px;
}
&.back {
color: #5C5C5C;
border: 2px solid #5C5C5C;
background-color: white;
}
&.next,
&.nextSecond,
&.nextThird,
&.nextFour,
&.nextFive,
&.nextSix,
&.nextSeven {
margin-right: 33px;
opacity: 0.3;
}
&.nextFour,
&.nextFive,
&.nextSix {
margin-right: -14px;
}
}
.active {
opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Question Page 3 -->
<div class="questionsPageThree hide">
<p class="number">3/7</p>
<div class="second">
<h1>
<span>Info</span>mentum
</h1>
<p class="hero">
<span class="start">
>
</span> Making change work</p>
</div>
<div class="q">
<div class="left">
<h2 class="three">3. Do you have someone who you feel comfortable sharing your feelings with?</h2>
</div>
<div class="opt">
<button class="options choosen" type="submit" value="3">
&check; Yes
</button>
<button class="options choosen" type="submit" value="0">
&#120 No
</button>
</div>
<div class="right">
<div class="image-right question3"></div>
</div>
<section class="q1">
<button class="btn btn-left back" value="BACK" type="button">
BACK
</button>
<button class="btn btn-right nextThird ans" value="NEXT" type="button" disabled="disabled">
NEXT
</button>
</section>
</div>
</div>
<!-- Question Page 4 -->
<div class="questionsPageFour hide">
<p class="number">4/7</p>
<div class="second">
<h1>
<span>Info</span>mentum
</h1>
<p class="hero">
<span class="start">
>
</span> Making change work</p>
</div>
<div class="q">
<div class="left">
<h2>4. How many times this week would you say you felt stressed to the point of worry?</h2>
</div>
<div class="opt">
<button class="options choosen" type="submit" value="3">
<h4> 0</h4>
<h6>TIMES</h6>
</button>
<button class="options choosen" type="submit" value="0">
<h4>1 - 2</h4>
<h6>TIMES</h6>
</button>
<button class="options choosen" type="submit" value="-2">
<h4>3 + </h4>
<h6>TIMES</h6>
</button>
</div>
<div class="right">
<div class="image-right question4"></div>
</div>
<section class="q1">
<button class="btn btn-left back" value="BACK" type="button">
BACK
</button>
<button class="btn btn-right nextFour ans" value="NEXT" type="button" disabled="disabled">
NEXT
</button>
</section>
</div>
</div>
javascript html jquery css class

Trying to change background color based off if the hour is in the past, current, or future

I am trying to change the background color based on if the current hour is past, present, or in the future.
Use case: I am building a day planner using moment.js. Every hour has its own field, ie: 8am, 9am, 10am. If the current time is 10:15am, I want 9am to be gray, 10am to be red, and 11am - 6pm to be green.
I am able to grab the current hour by using console.log(currentTime)
I am just trying to figure out how to build the function that changes the class background color. Any help would be greatly appreciated.
//current date and time
$("#currentDay").text(moment().format('ddd, MMM Do'));
//currentTime to determine if the hour matchs for color
var currentTime = moment().format('H');
console.log()
//todo project
// Use window.localStoirage to retrieve and store your data object as string
const LS = JSON.parse(localStorage.scheduler || '{}'); // now an Object
// double click makes calendar content editable
$(".textData").dblclick(function () {
$(this).addClass('d-none')
$(this).siblings("input").removeClass("d-none");
});
$(".btn").dblclick(function () {
console.log(this);
console.log($(this).attr("id"))
var id = $(this).attr("id")
var time = id.slice(0,3)
console.log(time)
var timeInputId = time + "Input";
});
// save makes edit end
// set active time
// make background color of / past hours gray / current hour red / future hours green
var hourPast = hourPast < currentTime;
var hourNow = currentTime;
var hourFuture = hourFuture < currentTime;
// if currentTime > hourNow make background color gray//
var hourNow = currentTime;
console.log(hourNow)
console.log(currentTime)
function backgroundColorEdit(){
if (hourNow == currentTime){
document.getElementsByClassName("backgroundTool").style.backgroundColor = "#ff0000";
}else if (hourNow < currentTime){
document.getElementsByClassName("backgroundTool").style.backgroundColor = "#d3d3d3";
}else
{
document.getElementsByClassName("backgroundTool").style.backgroundColor = "#90ee90";
}
}
// if currentTime = hourNow make background color Red //
// if currentTime < hourNow make background color green //
body {
font-family: 'Open Sans', sans-serif;
font-size: 16px;
line-height: 1;
}
textarea{
background: transparent;
border: none;
resize: none;
color: #000000;
border-left: 1px solid black;
padding: 10px;
}
.jumbotron {
text-align: center;
background-color: transparent;
color: black;
border-radius: 0;
border-bottom: 10px solid black;
}
.description{
white-space: pre-wrap;
}
.time-block{
text-align: center;
border-radius: 15px;
}
.row {
white-space: pre-wrap;
height: 80px;
border-top: 1px solid white;;
}
.hour {
background-color: #ffffff;
color: #000000;
border-top: 1px dashed #000000;
}
.past {
background-color: #d3d3d3;
color: white;
}
.present {
background-color: #ff6961;
color: white;
}
.future {
background-color: #77dd77;
color: white;
}
.saveBtn {
border-left: 1px solid black;
border-top-right-radius: 15px;
border-bottom-right-radius: 15px;
background-color: #06AED5;
color: white;
}
.saveBtn i:hover {
font-size: 20px;
transition: all .3s ease-in-out;
}
.red {
background-color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
/>
<link
rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.8.1/css/all.css"
integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf"
crossorigin="anonymous"
/>
<link
href="https://fonts.googleapis.com/css?family=Open+Sans&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="style.css" />
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<title>Work Day Scheduler</title>
</head>
<body>
<header class="jumbotron">
<h1 class="display-3">Work Day Scheduler</h1>
<p class="lead">A simple calendar app for scheduling your work day</p>
<p id="currentDay" class="lead"></p>
</header>
<div class="container">
<!-- Timeblocks go here -->
<div class="row">
<div class='col-2 hour'> 9am
</div>
<div class="col-8 description backgroundTool border-bottom scheduler">
<span class="textData 9amSpan">text here </span>
<input id="9amInput " class="d-none border-0 form-control textarea bg-transparent am9Input" type="text" placeholder="Default input">
</div>
<div class="col-2 saveBtn">
<button type="submit" id="9amButton" class="btn btn-primary mb-2 am9Button">Save</button>
</div>
</div>
<div class="row">
<div class='col-2 hour'> 10am
</div>
<div class="col-8 description backgroundTool border-bottom scheduler">
<span class="textData 10amSpan">text here </span>
<input id="10amInput" class="d-none border-0 form-control textarea bg-transparent am10Input" type="text" placeholder="Default input">
</div>
<div class="col-2 saveBtn">
<button type="submit" id="10amButton" class="btn btn-primary mb-2 am10Button">Save</button>
</div>
</div>
<div class="row">
<div class='col-2 hour'> 11am
</div>
<div class="col-8 description backgroundTool border-bottom scheduler">
<span class="textData 11amSpan">text here </span>
<input id="11amInput" class="d-none border-0 form-control textarea bg-transparent am11Input" type="text" placeholder="Default input">
</div>
<div class="col-2 saveBtn">
<button type="submit" id="11amButton" class="btn btn-primary mb-2 am11Button">Save</button>
</div>
</div>
<div class="row">
<div class='col-2 hour'> 12pm
</div>
<div class="col-8 description backgroundTool border-bottom scheduler">
<span class="textData 12pmSpan">text here </span>
<input id="12pmInput" class="d-none border-0 form-control textarea bg-transparent pm12Input" type="text" placeholder="Default input">
</div>
<div class="col-2 saveBtn">
<button type="submit" id="12amButton" class="btn btn-primary mb-2 pm12Button">Save</button>
</div>
</div>
<div class="row">
<div class='col-2 hour'> 1pm
</div>
<div class="col-8 description backgroundTool border-bottom scheduler">
<span class="textData 1pmSpan">text here </span>
<input id="1pmInput" class="d-none border-0 form-control textarea bg-transparent pm1Input" type="text" placeholder="Default input">
</div>
<div class="col-2 saveBtn">
<button type="submit" id="1pmButton" class="btn btn-primary mb-2 pm1Button">Save</button>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="script.js"></script>
</body>
</html>
Here's an idea (using a much-simplified version of your markup) that uses 24-hour time to do the comparisons like you were thinking.
Each row gets an id indicating which hour it represents, making it easy to compare the corresponding hour to the current hour.
const rows = document.getElementsByClassName("row");
let currentHour = parseInt(moment().format('H'));
Array.from(rows).forEach(row => {
let
rowIdString = row.id,
rowHour;
if (rowIdString) {
rowHour = parseInt(rowIdString);
}
if (rowHour) {
// Compares row id to current hour and sets color accordingly
if (currentHour === rowHour) {
setColor(row, "red");
} else if ((currentHour < rowHour) && (currentHour > rowHour - 6)) {
setColor(row, "green");
} else if ((currentHour > rowHour) && (currentHour < rowHour + 6)) {
setColor(row, "lightgrey");
} else {
setColor(row, "white");
}
}
});
function setColor(element, color) {
element.style.backgroundColor = color;
}
.row {
padding: 0.5em;
margin-bottom: 0.4em;
border: 1px solid gray;
border-radius: 0.5em;
}
<html lang="en">
<body>
<div class="row" id="9">
<span> 9am </span>
<span> -- text here -- </span>
<button id="9amButton">Save</button>
</div>
<div class="row" id="10">
<span>10am </span>
<span> -- text here -- </span>
<button id="10amButton">Save</button>
</div>
<div class="row" id="11">
<span>11am </span>
<span> -- text here -- </span>
<button id="11amButton">Save</button>
</div>
<div class="row" id="12">
<span>12pm </span>
<span> -- text here -- </span>
<button id="12pmButton">Save</button>
</div>
<div class="row" id="13">
<span> 1pm </span>
<span> -- text here -- </span>
<button id=" 1pmButton">Save</button>
</div>
<div class="row" id="14">
<span> 2pm </span>
<span> -- text here -- </span>
<button id=" 2pmButton">Save</button>
</div>
<div class="row" id="15">
<span> 3pm </span>
<span> -- text here -- </span>
<button id=" 3pmButton">Save</button>
</div>
<div class="row" id="16">
<span> 4pm </span>
<span> -- text here -- </span>
<button id=" 4pmButton">Save</button>
</div>
<div class="row" id="17">
<span> 5pm </span>
<span> -- text here -- </span>
<button id=" 5pmButton">Save</button>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
</body>
</html>

How to use $(this) selector to animate divs with the same class?

I have two divs, with the same class name of .pageSlide. When I click on the button with class name .moveup or .movedown, I specifically want that button's respective div to slide up or down. At the moment, if I click on the button associated with say, div A, then div B also animates. I'm guessing I need a $(this) selector in the JS somewhere. I'm not sure.
Here's a jsfiddle of working code
https://jsfiddle.net/hpe459ok/
Essentially I have this:
$('.moveup').click(function() {
if ($('.pageSlide').css('top') == '-420px') {
$('.pageSlide').animate({
top: '0'
}, 700);
} else {
$('.pageSlide').animate({
top: '0'
}, 700);
}
});
$('.movedown').click(function() {
if ($('.pageSlide').css('top') == '0') {
$('.pageSlide').animate({
top: '420'
}, 500);
} else {
$('.pageSlide').animate({
top: '420'
}, 500);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container1">
<div class="page1">
content
<button class="moveup">Next page</button>
</div>
<div class="page2 pageSlide">
content
<button class="movedown">Previous page</button>
</div>
</div>
<div class="container2">
<div class="page1">
content
<button class="moveup">Next page</button>
</div>
<div class="page2 pageSlide">
content
<button class="movedown">Previous page</button>
</div>
</div>
Try using the below code:
$('.moveup').click(function() {
$(this).closest(".page1").siblings('.pageSlide').animate({
top: '0'
}, 700);
});
$('.movedown').click(function() {
$(this).closest(".page2").animate({
top: '420'
}, 500);
});
I would use data attributes on your .moveup and .movedown buttons. By setting an attribute data-parent to be the id of the top level parent <div> it becomes trivial to modify your existing functions to handle the proper animations.
$('.moveup').click(function() {
var parent = $(this).data('parent');
if ($('#'+parent).find('.pageSlide').css('top') == '-420px') {
$('#'+parent).find('.pageSlide').animate({
top: '0'
}, 700);
} else {
$('#'+parent).find('.pageSlide').animate({
top: '0'
}, 700);
}
});
$('.movedown').click(function() {
var parent = $(this).data('parent');
if ($('#'+parent).find('.pageSlide').css('top') == '0') {
$('#'+parent).find('.pageSlide').animate({
top: '420'
}, 500);
} else {
$('#'+parent).find('.pageSlide').animate({
top: '420'
}, 500);
}
});
.pageSlide {
position: absolute;
left: 0;
right: 0;
top: 0;
height: 400px;
background: ghostwhite;
z-index: 0;
}
.page2 {
z-index: 1;
top: 420px;
}
.image-wrapper {
height: 400px;
overflow: hidden;
position: relative;
text-align: center;
border: black 1px solid;
}
.overlay-left {
background-color: white;
}
.overlay-right {
background-color: white;
}
.image-overlay-content-left {
background-color: white;
}
.image-overlay-content-right {
background-color: white
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="small-12 columns" id="nominate">
<div class="image-wrapper overlay overlay-left">
<div class="image-overlay-content image-overlay-content-left" id="formslide">
<form id="foo" method="post" name="nomForm" action="nominate-test.html#thankyou">
<div class="page1">
<label class="row">
<h2 class="headline">Your name</h2>
<input placeholder="e.g. John Smith" type="text" name="name" id="name" tabindex="1" autofocus>
<span id="nameError" class="error headline"></span>
</label>
<label class="row email">
<h2 class="headline">Your email address</h2>
<input placeholder="example#rofordaward.co.uk" type="text" name="email" id="email" tabindex="2">
<span id="emailError" class="error headline"></span>
</label>
<label class="row">
<h2 class="headline">Company name</h2>
<input placeholder="e.g. Roford" type="text" name="company" id="company" tabindex="3">
<span id="companyError" class="error headline"></span>
</label>
<div class="next">
<button type="button" class="moveup" data-parent="nominate">Next page</button><i class="icon-down-open"></i></div>
</div>
<div class="pageSlide page2">
<label class="row reason">
<h2 class="headline">Reason for nomination</h2>
<textarea id="textarea" rows="6" cols="25" maxlength="1000" name="message" id="message" placeholder="A brief evidence based summary"></textarea>
<span id="messageError" class="error headline"></span>
<div id="text-area-wrap">
<div id="textarea_feedback"></div>
</div>
</label>
<div class="row button-wrap">
<div class="column small-12">
<input class="button" name="submit" type="submit" id="contact-submit" value="Submit">
</div>
</div>
<div class="prev">
<button type="button" class="movedown" data-parent="nominate">Previous page</button><i class="icon-up-open"></i></div>
</div>
</form>
</div>
</div>
</div>
<div class="small-12 columns" id="apply">
<div class="image-wrapper overlay overlay-right">
<div class="overlay-option-headline overlay-option-headline-right">
<h5>Tell us why you're a great business</h5>
<h1 class="headline">Apply</h1>
</div>
<div class="image-overlay-content image-overlay-content-right">
<div class="page1">
<h2 class="headline">Application Form</h2>
<div class="row apply-points">
<div class="column small-12">
<h5>Please make sure you have read our Criteria page and terms and conditions in full before applying.</h5></div>
<div class="column small-12">
<h5>Ensure you have gathered evidence to support your application.</h5></div>
<div class="column small-12">
<h5>Shortlisted companies will be contacted with further instructions.</h5></div>
</div>
<div class="next">
<button type="button" class="moveup" data-parent="apply">Next page</button><i class="icon-down-open"></i></div>
</div>
<div class="page2 pageSlide">
<h2 class="headline">Contact name</h2>
<div class="row apply-points">
<div class="column small-12">
<h5>aduhwijdaduhwijdaduhwijd aduhwijd aduhwijd aduhwijd aduhwijd aduhwijd aduhwijd aduhwijd aduhwijdaduhwijdaduhwijdaduhwijdaduhwijdad aduhwijd aduhwijd aduhwijdaduhwijd aduhwijd ijdaduhwijdaduhwijdaduhwijdaduhwijdad aduhwijd aduhwijd aduhwijdaduhwijd aduhwijd</h5></div>
</div>
<div class="prev">
<button type="button" class="movedown" data-parent="apply">Previous page</button><i class="icon-up-open"></i></div>
</div>
</div>
</div>
</div>

Categories