Countdown before download only working on 1st button - javascript

I have got this Download button with a few seconds Timer before download but unfortunately, it is working only on 1st button but not on other buttons.
I want it to work on each and every download button properly and I am not able to figure out how to fix this issue. Please help!
I have Attached a CSS, HTML, and JavaScript that I have been using.
document.getElementById("download_button").addEventListener("click", function(event) {
event.preventDefault();
var timeleft = 3;
var downloadTimer = setInterval(function function1() {
document.getElementById('download').style.display = "none";
document.getElementById("timer").innerHTML = "Wait " + timeleft + "";
if (timeleft <= 0) {
clearInterval(downloadTimer);
document.getElementById("timer").innerHTML = ""
window.open(document.querySelector('#downloadbutton a').href, '_blank');
document.getElementById('download').style.display = "";
}
timeleft -= 1;
}, 1000);
});
.container {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
#download_button {
border: none;
margin-top: 0px;
padding: 10px;
width: 200px;
font-family: "montserrat", sans-serif;
text-transform: uppercase;
border-radius: 6px;
cursor: pointer;
color: #fff;
font-size: 16px;
transition: 0.4s;
line-height: 28px;
outline: none;
}
.button-1 {
background: #f12711;
}
.button-2 {
background: #0575E6;
}
.button-3 {
background: #fe8c00;
}
#download_button:hover {
background: #000000;
}
.title {
font-weight: bold;
}
<div id="downloadbutton" style="text-align: center;">
<a href="http:///www.google.com">
<button id="download_button" class="button-1">
<div class="title">Document Title 1</div>
<div id="download">DOWNLOAD</div>
<div id="timer"></div>
</button>
</a>
</div>
<br>
<div id="downloadbutton" style="text-align: center;">
<a href="http:///www.google.com">
<button id="download_button" class="button-2">
<div class="title">Document Title 2</div>
<div id="download">DOWNLOAD</div>
<div id="timer"></div>
</button>
</a>
</div>
<br>
<div id="downloadbutton" style="text-align: center;">
<a href="http:///www.google.com">
<button id="download_button" class="button-3">
<div class="title">Document Title 3</div>
<div id="download">DOWNLOAD</div>
<div id="timer"></div>
</button>
</a>
</div>

Simple solution using different IDs
function download(btn) {
id = Number(btn.id.slice("downloadbutton".length+1))
var timeleft = 3;
var downloadTimer = setInterval(function function1() {
document.getElementById('download' + id).style.display = "none";
document.getElementById("timer" + id).innerHTML = "Wait " + timeleft + "";
if (timeleft <= 0) {
clearInterval(downloadTimer);
document.getElementById("timer" + id).innerHTML = ""
//window.open(document.querySelector('#downloadbutton' + id + ' a').href, '_blank');
document.getElementById('download' + id).style.display = "";
}
timeleft -= 1;
}, 1000);
}
.container {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
#download_button {
border: none;
margin-top: 0px;
padding: 10px;
width: 200px;
font-family: "montserrat", sans-serif;
text-transform: uppercase;
border-radius: 6px;
cursor: pointer;
color: #fff;
font-size: 16px;
transition: 0.4s;
line-height: 28px;
outline: none;
}
.button-1 {
background: #f12711;
}
.button-2 {
background: #0575E6;
}
.button-3 {
background: #fe8c00;
}
#download_button:hover {
background: #000000;
}
.title {
font-weight: bold;
}
<div id="downloadbutton1" style="text-align: center;">
<button id="download_button1" class="button-1" onclick="download(this)">
<div class="title">Document Title 1</div>
<div id="download1">DOWNLOAD</div>
<div id="timer1"></div>
</button>
</div>
<br>
<div id="downloadbutton2" style="text-align: center;">
<button id="download_button2" class="button-2" onclick="download(this)">
<div class="title">Document Title 2</div>
<div id="download2">DOWNLOAD</div>
<div id="timer2"></div>
</button>
</div>
<br>
<div id="downloadbutton3" style="text-align: center;">
<button id="download_button3" class="button-3" onclick="download(this)">
<div class="title">Document Title 3</div>
<div id="download3">DOWNLOAD</div>
<div id="timer3"></div>
</button>
</div>

You are missing the basic rule of html,
The simple difference between the two is that while a class can be
used repeatedly on a page, an ID must only be used once per page.
Therefore, it is appropriate to use an ID on the div element that is
marking up the main content on the page, as there will only be one
main content section. In contrast, you must use a class to set up
alternating row colors on a table, as they are by definition going to
be used more than once...
Source: Whats-the-difference-between-an-id-and-a-class
Either you can use classes or you can use different ids, or both depending on requirements.
I have changed download_button from id to class and added EventListener with loop, the reason of using class is you are adding same EventListener to all buttons.
Then I have used different but identical Ids to download, downloadbutton and timer because your function need to select them individually, I used numbers with Id because it will be easy to select with the index of the item.
document.querySelectorAll(".download_button").forEach(function(item, index) {
item.addEventListener("click", function(event) {
event.preventDefault();
var timeleft = 3;
var downloadTimer = setInterval(function function1() {
document.getElementById('download_' + index).style.display = "none";
document.getElementById("timer_" + index).innerHTML = "Wait " + timeleft + "";
if (timeleft <= 0) {
clearInterval(downloadTimer);
document.getElementById("timer_" + index).innerHTML = ""
window.open(document.querySelector('#downloadbutton' + index + ' a').href, '_blank');
document.getElementById('download_' + index).style.display = "";
}
timeleft -= 1;
}, 1000);
});
})
.container {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
.download_button {
border: none;
margin-top: 0px;
padding: 10px;
width: 200px;
font-family: "montserrat", sans-serif;
text-transform: uppercase;
border-radius: 6px;
cursor: pointer;
color: #fff;
font-size: 16px;
transition: 0.4s;
line-height: 28px;
outline: none;
}
.button-1 {
background: #f12711;
}
.button-2 {
background: #0575E6;
}
.button-3 {
background: #fe8c00;
}
.download_button:hover {
background: #000000;
}
.title {
font-weight: bold;
}
<div id="downloadbutton0" style="text-align: center;">
<a href="http:///www.google.com">
<button class="download_button button-1">
<div class="title">Document Title 1</div>
<div id="download_0">DOWNLOAD</div>
<div id="timer_0"></div>
</button>
</a>
</div>
<br>
<div id="downloadbutton1" style="text-align: center;">
<a href="http:///www.google.com">
<button class="download_button button-2">
<div class="title">Document Title 2</div>
<div id="download_1">DOWNLOAD</div>
<div id="timer_1"></div>
</button>
</a>
</div>
<br>
<div id="downloadbutton2" style="text-align: center;">
<a href="http:///www.google.com">
<button class="download_button button-3">
<div class="title">Document Title 3</div>
<div id="download_2">DOWNLOAD</div>
<div id="timer_2"></div>
</button>
</a>
</div>

Related

How to achieve different reactions at the first and second button click when there are many the same buttons? (Filter in js)

there is a filter on the js, which consists of three identical buttons (named "green", "yellow", "red"), which are responsible for setting/removing the blur effect for the set of pictures located below.
When pressing the "green" button, a blur effect should be set for all pictures that have a value "green" of data-card property.
At the second click on the same button, the blur effect should be canceled for this category of pictures.
I solved this problem with a reception with a boolean flag:
let firstClick = true;
if (firstClick){
//..do at first click
firstClick = !firstClick;
}
else{
//..do at second click
firstClick = !firstClick;
}
However, the problem occurs when I click on the "green" button (this is the first click on the "green" button), and after that on another button, for example "red" (this is the first click on the "red" button). But the compiler perceives a click on the "red" button as a second click, although it is a different button.
The question is how to distinguish the behavior in different buttons?
In general, I solved the problem through a complete search and many if statements. Maybe there is an alternative way?
Project demo in codepen
//main.js
function app() {
const buttons = document.querySelectorAll('.service__btn');
const cards = document.querySelectorAll('.service__item');
let firstClick = true;
function setBlour(listOfCards) {
listOfCards.forEach(item => {
if (item.classList.contains(currentCategory)) {
item.classList.add('blur');
}
});
}
function resetBlour(listOfCards) {
listOfCards.forEach(item => {
if (item.classList.contains(currentCategory)) {
item.classList.remove('blur');
}
});
}
function highlightButton(butt) {
if (!butt.classList.contains('service__btn__clicked')) {
butt.classList.add('service__btn__clicked');
}
firstClick = !firstClick;
}
function unhighlight(butt) {
if (butt.classList.contains('service__btn__clicked')) {
butt.classList.remove('service__btn__clicked');
}
firstClick = !firstClick;
}
buttons.forEach(button => {
button.addEventListener('click', (event) => {
currentCategory = event.target.dataset.filter; //current category we get from clicked button
let matchedCards = document.querySelectorAll(`[data-card="${button.dataset.filter}"]`);
//is it first click?
if (firstClick) {
if (!matchedCards[0].classList.contains('blur')) { // each click we have set of matchedCards, it's easy to check one of them (the first for example) if it have blur
setBlour(matchedCards);
highlightButton(button);
} else { //it is a first clcik, but card have blur - so remove blur
resetBlour(matchedCards);
unhighlight(button);
}
}
//second click
else {
if (!matchedCards[0].classList.contains('blur')) { //if there is no blur - add blur
setBlour(matchedCards);
highlightButton(button);
} else { //second click and blur is present - so we need to remove it
resetBlour(matchedCards);
unhighlight(button);
}
}
});
});
}
app()
html {
box-sizing: border-box;
}
*,
*::before,
*::after {
box-sizing: inherit;
}
body {
margin: 0;
padding: 0;
}
a {
text-decoration: none;
}
li {
list-style-type: none;
}
.container {
width: 1220px;
margin: 0 auto;
}
.service {
background: #EDF2EC;
padding-top: 40px;
padding-bottom: 70px;
}
.service__top {
display: flex;
align-items: center;
margin-bottom: 20px;
}
.service__top-title {
font-family: 'Inika', serif;
font-weight: 400;
font-size: 40px;
line-height: 52px;
color: #499A18;
max-width: 306px;
}
.service__filter-btn {
margin-left: 142px;
}
.service__btn {
border: 1px solid #E06733;
border-radius: 5px;
padding: 12px 40px;
font-family: 'Inika', serif;
font-weight: 400;
font-size: 20px;
line-height: 26px;
color: #E06733;
}
.service__btn__clicked {
background: #E06733;
border: 1px solid #E06733;
border-radius: 5px;
color: #FFFFFF;
}
.service__btn+.service__btn {
margin-left: 32px;
}
.service__content {
column-count: 3;
gap: 0 116px;
}
.service__item {
margin-bottom: 55px;
text-align: center;
width: 330px;
height: 350px;
border-radius: 20px;
}
.red {
background-color: red;
}
.green {
background-color: green;
}
.yellow {
background-color: yellow;
}
.service__item-title {
font-family: 'Inter', sans-serif;
font-weight: 700;
font-size: 20px;
line-height: 20px;
color: #E06733;
margin-top: 10px;
margin-bottom: 10px;
}
.service__item-text {
font-family: 'Inter', sans-serif;
font-weight: 400;
font-size: 16px;
line-height: 20px;
color: #717171;
margin-bottom: 36px;
}
.service__item-description {
border-radius: 0px 0px 20px 20px;
border: 1px solid #e3e1d5;
display: none;
}
.blur {
filter: blur(5px);
}
.animation {
transform: scale(0);
opacity: 0;
}
<body>
<section class="service">
<div class="container">
<div class="service__top">
<h3 class="service__top-title">
Caption and Description
</h3>
<div class="service__filter-btn">
<button class="service__btn service__btn-type_green" data-filter="green"> Green</button>
<button class="service__btn service__btn-type_yellow" data-filter="yellow">Yellow</button>
<button class="service__btn service__btn-type_red" data-filter="red">Red</button>
</div>
</div>
<div class="service__content">
<div class="service__item green" data-card="green">
<div class="service__item-description">
<h4 class="service__item-title">Green color</h4>
<p class="service__item-text">Description</p>
</div>
</div>
<div class="service__item red" data-card="red">
<div class="service__item-description">
<h4 class="service__item-title">Red color</h4>
<p class="service__item-text">Description</p>
</div>
</div>
<div class="service__item yellow" data-card="yellow">
<div class="service__item-description">
<h4 class="service__item-title">Yellow color</h4>
<p class="service__item-text">Description</p>
</div>
</div>
<div class="service__item red" data-card="red">
<div class="service__item-description">
<h4 class="service__item-title">Red color</h4>
<p class="service__item-text">Description</p>
</div>
</div>
<div class="service__item green" data-card="green">
<div class="service__item-description">
<h4 class="service__item-title">Green color</h4>
<p class="service__item-text">Description</p>
</div>
</div>
<div class="service__item red" data-card="red">
<div class="service__item-description">
<h4 class="service__item-title">Red color</h4>
<p class="service__item-text">Description</p>
</div>
</div>
</div>
</div>
</section>
</body>

Multiple Slideshow not working properly. Any Clue?

So basically, I'm trying to create multiple slideshows on the page with dots to switch between the slides (because I've already tried the arrow type button and it doesn't workout for me idk), and the issue is that when I use more than one slideshow the dots on the first one either stop working or begin switching the below slideshows slides.
I have already seen a lot of threads about this issue and tried several answers to them, but none of them seem to work. So if anybody has any clue of what is happening in my code and knows the answer, it would be great. PD: I'm sorry if it contains any grammatic faults :c.
This is the code I'm using (originally from w3s: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_quotes_slideshow and https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_slideshow_multiple)
/* Referencia miscelánea de assets
color cuadraos: #31572C
color fondo global: #B3B882
color fondo variable: #90A970
color fondo recuadros: #4F772D
color fondo titulo principal&Home: #132A13
color flechas: #000000
*/
* {
font-family: 'Roboto', sans-serif;
font-size:large;
}
details {
border: 1px solid #d4d4d400;
margin-top: 10px;
}
summary {
font-weight: bold;
font-size: 120%;
margin: -.75em -.75em 0;
padding: .75em;
background-color:#31572C;
color: #fff;
}
details[open] {
padding: 10px;
}
details[open] summary {
margin-bottom: 10px;
}
#chingue {
text-align: center;
}
/* Cuadrados principales*/
.TituloEleccion {
color: #ffffff;
background-color: #31572C;
text-align: center;
height: 99%;
width:100%;
margin-top:0%;
line-height: 3.1;
}
body {
background-color: #B3B882;
}
#titulogeneral {
color: #ffffff;
background-color: #132A13;
border-style: ridge;
border-color: #4eaa4e;
margin-left: 20%;
margin-right: 20%;
height: 8.5%;
text-align: center;
line-height: 4.15;
white-space: nowrap;
overflow: hidden;
white-space: initial;
}
.colordesconocido {
background-color: #4F772D;
width:100%;
margin-top:0%;
margin-bottom: 30px;
}
#fondouniversal {
background-color:#B3B882 ;
}
.divinformacion {
width: 50%;
display: block;
float: left;
padding: 20px;
border: 2px solid rgb(0, 0, 0);
border-style: double;
border-radius: 10px;
}
.fondoeleccion {
color: #000000;
background-color: #4F772D;
width:100%;
margin-top:0%;
border: 1.5px solid rgb(0, 0, 0);
border-style: double;
margin-bottom: 30px;
}
img{
border:2px solid #000000;
}
body {
font-family:"Pathway Gothic One", sans-serif;
}
.hidecontent {
display: none;
}
#myaccordion label {
box-shadow:0 0 20px #d4d4d4;
display: block;
padding: 8px 22px;
margin: 1px 0px 1px 0px;
cursor: pointer;
background: #31572C;
color: #FFF;
transition: ease .5s;
text-align:center;
}
#myaccordion label:hover {
background: #31572C;
}
.content {
box-shadow:0 0 20px #d4d4d4;
background: #90A970;
padding: 1.5% 1.5%;
border: 1px solid #d4d4d4;
margin: -1 0 0 0;
}
#myaccordion input:checked + label + .content {
display: block;
-moz-animation: fadeIn 0.5s ease-out;
-o-animation: fadeIn 0.5s ease-out;
animation: fadeIn 0.5s ease-out;
}
#info1 {
float:right;
}
#foto {
float:left;
}
* {box-sizing: border-box}
body {font-family: Verdana, sans-serif; margin:0}
/* Slideshow container */
.slideshow-container0 {
position: relative;
background:#90A970;
}
.slideshow-container1 {
position: relative;
background:#90A970;
}
.slideshow-container2 {
position: relative;
background:#90A970;
}
/* Slides */
.mySlides0 {
display: none;
padding: 2px;
text-align: center;
}
.mySlides1 {
display: none;
padding: 2px;
text-align: center;
}
.mySlides2 {
display: none;
padding: 2px;
text-align: center;
}
/* The dot/bullet/indicator container */
.dot-container0 {
text-align: center;
padding: 20px;
background:#31572C;
}
.dot-container1 {
text-align: center;
padding: 20px;
background:#31572C;
}
.dot-container2 {
text-align: center;
padding: 20px;
background:#31572C;
}
/* The dots/bullets/indicators */
.dot {
cursor: pointer;
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}
.dot0 {
cursor: pointer;
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}
.dot1 {
cursor: pointer;
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}
.dot2 {
cursor: pointer;
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}
/* Add a background color to the active dot/circle */
.active, .dot:hover {
background-color: #717171;
}
.titulilloparque {
text-align: center;
color:#000000;
}
<html>
<head>
<title>PARQUES NATURALES Y NACIONALES. ANDALUCIA</title>
<link rel="stylesheet" href="CSSMAIN.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
</head>
<a id="inicio"></a>
<body id="fondouniversal">
<div>
<p><h1 id="titulogeneral">PARQUES NATURALES Y NACIONALES. ANDALUCIA</h1></p>
</div>
<div id="myaccordion">
<input type="checkbox" id="accordion1" class="hidecontent"/>
<label for="accordion1"><h2>PARQUES NATURALES</h2></label>
<div class="content hidecontent">
<div class="fondoeleccion">
<h3 class="titulilloparque">PARQUE NATURAL DE SIERRA NEVADA</h3>
<div class="slideshow-container0">
<div class="mySlides0 fade">
<img src="images/FotoSN1.jpg" style="width:65%" style="height:25%"/>
<div>Imagen del parque</div>
</div>
<div class="mySlides0">
<p> <h4>DATOS</h4>
GEOLOCALIZACIÓN: 37°05'19.8''N 3°10'18.7''O <br/>
Hotel, casa rural y cabaña.<br/>
Senderismo, alpinismo, rutas en bicicleta, esquí, snowboard,
clases de esquí y snowboard guiadas<br/>
Jabalí, gato montés, zorro, comadreja, garduña, gineta,
y el frecuente turón común <br/>
</p>
</div>
<div class="mySlides0">
<p> <h4>TURISMO</h4>
TOTAL<br/>
VIAJEROS 3712<br/>
PERNOCTACIONES 8430<br/>
EST. MEDIA 2,27 d<br/><br/>
ESPAÑOLES<br/>
VIAJEROS 2235<br/>
PERNOCTACIONES 5558<br/>
EST. MEDIA 2,49 d<br/><br/>
EXTRANJEROS<br/>
VIAJEROS 1477<br/>
PERNOCTACIONES 2872<br/>
EST. MEDIA 1,94 d<br/>
</p>
</div>
</div>
<div class="dot-container0">
<span class="dot0" onclick="moverprimero(1)"></span>
<span class="dot0" onclick="moverprimero(2)"></span>
<span class="dot0" onclick="moverprimero(3)"></span>
</div>
<script>
var slideIndex1 = 2;
showSlides(slideIndex1);
function plusSlides(n) {
showSlides(slideIndex1 += n);
}
function moverprimero(n) {
showSlides(slideIndex1 = n);
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("mySlides0");
var dots = document.getElementsByClassName("dot0");
if (n > slides.length) {slideIndex1 = 1}
if (n < 1) {slideIndex1 = slides.length}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex1-1].style.display = "block";
dots[slideIndex1-1].className += " active";
}
</script>
🏚
</div>
<div class="fondoeleccion">
<h3 class="titulilloparque">PARQUE NATURAL SIERRA DE LAS NIEVES</h3>
<div class="slideshow-container1">
<div class="mySlides1 fade">
<img src="images/FOTOSdN1.jpg" style="width:65%" style="height:25%">
<div>Imagen del parque</div>
</div>
<div class="mySlides1">
<p> <h4>DATOS</h4>
GEOLOCALIZACIÓN: 36°44'N 4°59'O <br>
Hotel y casa rural.<br>
Rutas de senderismo, rutas en bicicleta,
rutas en 4x4 y observatorio de aves.<br>
Íbice ibérico, gato montés, zorro, comadreja,
garduña, gineta, turón común.<br>
</p>
</div>
<div class="mySlides1">
<p> <h4>TURISMO</h4>
TOTAL<br>
VIAJEROS 2928<br>
PERNOCTACIONES 5415<br>
EST. MEDIA 1'85 d<br><br>
ESPAÑOLES<br>
VIAJEROS 1245<br>
PERNOCTACIONES 2041<br>
EST. MEDIA 1'64 d<br><br>
EXTRANJEROS<br>
VIAJEROS 1683<br>
PERNOCTACIONES 3374<br>
EST. MEDIA 2 d<br>
</p>
</div>
</div>
<div class="dot-container1">
<span class="dot1" onclick="moversegundo(1)"></span>
<span class="dot1" onclick="moversegundo(2)"></span>
<span class="dot1" onclick="moversegundo(3)"></span>
</div>
<script>
var slideIndex2 = 1;
showSlides(slideIndex2);
function plusSlides(n) {
showSlides(slideIndex2 += n);
}
function moversegundo(n) {
showSlides(slideIndex2 = n);
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("mySlides1");
var dots = document.getElementsByClassName("dot1");
if (n > slides.length) {slideIndex2 = 1}
if (n < 1) {slideIndex2 = slides.length}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex2-1].style.display = "block";
dots[slideIndex2-1].className += " active";
}
</script>
🏚
</div>
<div class="fondoeleccion">
<h3 class="titulilloparque">PARQUE NATURAL DE LA BREÑA Y MARISMAS DE BARBATE</h3>
<div class="slideshow-container2">
<div class="mySlides2 fade">
<img src="images/FOTOBMB1.jpg" style="width:65%" style="height:25%">
<div>Imagen del parque</div>
</div>
<div class="mySlides2">
<p> <h4>DATOS</h4>
GEOLOCALIZACIÓN: 36°10'44''N 5°58'22''O <br>
Hotel y casa rural.<br>
Inmersión submarina, surf, observación de aves,
rutas de senderimos y la destaca visita al tajo vertical de
los Acantilados de Barbate.<br>
Principalmente fauna aviar; gaviota argéntea,
garcilla bueyera, garcetas, vencejo, mirlo, cárabo, carbonero, etc.<br>
</p>
</div>
<div class="mySlides2">
<p> <h4>TURISMO</h4>
TOTAL<br>
VIAJEROS 2188<br>
PERNOCTACIONES 7363<br>
EST. MEDIA 3,37 d<br><br>
ESPAÑOLES<br>
VIAJEROS 1417<br>
PERNOCTACIONES 3744<br>
EST. MEDIA 2,64 d<br><br>
EXTRANJEROS<br>
VIAJEROS 771<br>
PERNOCTACIONES 3619<br>
EST. MEDIA 4,69 d<br>
</p>
</div>
</div>
<div class="dot-container2">
<span class="dot2" onclick="movertercero(1)"></span>
<span class="dot2" onclick="movertercero(2)"></span>
<span class="dot2" onclick="movertercero(3)"></span>
</div>
<script>
var slideIndex3 = 1;
showSlides(slideIndex3);
function movertercero(n) {
showSlides(slideIndex3 = n);
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("mySlides2");
var dots = document.getElementsByClassName("dot2");
if (n > slides.length) {slideIndex3 = 1}
if (n < 1) {slideIndex3 = slides.length}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex3-1].style.display = "block";
dots[slideIndex3-1].className += " active";
}
</script>
🏚
</div>
</div>
</body>
</html>
This code wont work because there's a problem with
your JavaScript as some variables are conflicting
I will suggest you to make separate JavaScript file first and include it in your index.html like this ;
<scritp src=" *your JavaScript file path* "> </script>
this way your code is separated and it'll be easy to determine problems in your code.
well after this follow the same pattern as per link you provided of w3cSchool.
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_quotes_slideshow and https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_slideshow_multiple)
commented out things that you should resolve according to your requirement;
these first two are the default one 3rd is my added one just like this you have to add yourself in the code
<p>Slideshow 1:</p>
<div class="slideshow-container">
<div class="mySlides1">
<img src="img_nature_wide.jpg" style="width:100%">
</div>
<div class="mySlides1">
<img src="img_snow_wide.jpg" style="width:100%">
</div>
<div class="mySlides1">
<img src="img_mountains_wide.jpg" style="width:100%">
</div>
<a class="prev" onclick="plusSlides(-1, 0)">❮</a>
<a class="next" onclick="plusSlides(1, 0)">❯</a>
</div>
<p>Slideshow 2:</p>
<div class="slideshow-container">
<div class="mySlides2">
<img src="img_band_chicago.jpg" style="width:100%">
</div>
<div class="mySlides2">
<img src="img_band_la.jpg" style="width:100%">
</div>
<div class="mySlides2">
<img src="img_band_ny.jpg" style="width:100%">
</div>
<a class="prev" onclick="plusSlides(-1, 1)">❮</a>
<a class="next" onclick="plusSlides(1, 1)">❯</a>
</div>
<p>Slideshow 3:</p>
<div class="slideshow-container">
<div class="mySlides3"> //NEW CLASS ADDED further more class can be added like this like 4 5 6....and so on
<img src="img_band_chicago.jpg" style="width:100%">
</div>
<div class="mySlides3">
<img src="img_band_la.jpg" style="width:100%">
</div>
<div class="mySlides3">
<img src="img_band_ny.jpg" style="width:100%">
</div>
here I added new number 2 as first two have 0 and 1 now 2 for third slide and 3 4 5.. and so on for more slides to be added watch out these should be added on y-axis as x-axis is responsible for no of jumps one slide should make
<a class="prev" onclick="plusSlides(-1, 2)">❮</a>
<a class="next" onclick="plusSlides(1, 2)">❯</a>
</div>
<script>
var slideIndex = [1, 1, 1]; //here array with value will be added for further increase in slides
var slideId = ["mySlides1", "mySlides2", "mySlides3"] // new classes will be added here
showSlides(0, 0);
showSlides(1, 1);
showSlides(0, 2); //this will increase as well depending upon the no. of slides you'll add
function plusSlides(n, no) {
showSlides(slideIndex[no] += n, no);
}
function showSlides(n, no) {
var i;
var x = document.getElementsByClassName(slideId[no]);
if (n > x.length) {slideIndex[no] = 1}
if (n < 1) {slideIndex[no] = x.length}
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
x[slideIndex[no]-1].style.display = "block";
}
</script>
</body>
</html>

How can I use parentNode with add/removeClass and an IF argument for <audio>?

I have multiple <audio> containers. When pressing 'Play' I want to target the parent audio container to play instead of all the other containers.
Each time I press the play button, all the audio containers fire and start playing. What I want is to target the parent container of the pressed button and only play that container.
I understand that I can use parentNode for this but whenever I implement it, I get an error, whether I use it for the IF argument or the add/removeClass syntax.
function playAudio(val) {
var aud = $("audio")[val - 1];
if (aud.paused) {
aud.play();
aud.loop = false;
$(".play-pause").removeClass("icon-play");
$(".play-pause").addClass("icon-stop");
} else {
aud.pause();
$(".play-pause").removeClass("icon-stop");
$(".play-pause").addClass("icon-play");
}
aud.ontimeupdate = function () {
$(".progress")
.css("width", (aud.currentTime / aud.duration) * 100 + "%");
var mins = Math.floor(aud.currentTime / 60);
if (mins < 10) {
mins = "0" + String(mins);
}
var secs = Math.floor(aud.currentTime % 60);
if (secs < 10) {
secs = "0" + String(secs);
}
$(".timestamp")
.text(mins + ":" + secs);
};
}
.player {
position: relative;
display: flex;
border-radius: 0px;
padding: 5 16px;
}
.player .info {
display: flex;
flex-flow: column nowrap;
justify-content: center;
width: 50%;
padding: 0 16px;
}
.player .info .name {
font-size: 15px;
font-weight: 700;
}
.player .info .singer {
font-size: 12px;
}
.player .audioBtns {
width: 50%;
/*align-items: center;*/
padding: 0 16px;
}
.player .audioBtns div:nth-child(1) {
font-size: 30px;
}
.player .audioBtns div:nth-child(2),
.player .audioBtns div:nth-child(3) {
font-size: 18px;
}
.player .progress {
position: absolute;
height: 5px;
left: 0;
bottom: 0;
background-color: #f8f9fa;
border-radius: 0px;
}
.icon-loop {
content: url("loop.svg");
width: 20px;
height: 20px;
display: block;
}
.icon-play:before {
content: url("https://image.flaticon.com/icons/svg/860/860768.svg");
width: 30px;
height: 45px;
display: block;
}
.icon-stop:before {
content: url("https://image.flaticon.com/icons/svg/633/633940.svg");
width: 30px !important;
height: 40px !important;
display: block;
}
.playBtn {
padding: 0 16px;
}
.activeOverlay {
filter: invert(42%) sepia(11%) saturate(1216%) hue-rotate(279deg)
brightness(88%) contrast(85%);
}
.audioContainer {
background-color: #d3d3d3;
padding: 2% 2% !important;
}
.audioContainer:not(:last-child) {
margin-bottom: 3%;
}
.audioContainerActive {
background-color: #855b6f !important;
color: #f8f9fa !important;
}
.IconActive {
filter: invert(92%) sepia(17%) saturate(3434%) hue-rotate(186deg)
brightness(127%) contrast(95%);
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- First Audio Container. OnClick on Line 5 -->
<div class="row no-gutters d-flex flex-column col-12">
<div class="col d-flex flex-column justify-content-xl-center audioContainer">
<div class="player">
<div class="d-flex flex-row align-items-xl-center playBtn" onclick="playAudio(1)"><i class="fas fa-pause iconfont play-pause icon-play"></i></div><audio src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3" type="audio/mpeg"></audio>
<div class="info">
<div class="name">
<p id="qwewq">By The Shell</p>
</div>
<div class="singer">
<p>Adam M.</p>
</div>
</div>
<div class="d-flex flex-row justify-content-around justify-content-xl-end align-items-xl-center audioBtns">
<p class="timestamp" style="font-size: 20px;margin-bottom: 0px;">00:00</p>
</div>
<div data-toggle="tooltip" id="progressBar" class="progress"></div>
</div>
</div>
<!-- Second Audio Container. OnClick on Line 25 -->
<div class="col d-flex flex-column justify-content-xl-center audioContainer">
<div class="player">
<div class="d-flex flex-row align-items-xl-center playBtn" onclick="playAudio(2)"><i class="fas fa-pause iconfont play-pause icon-play"></i></div><audio src="https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3" type="audio/mpeg"></audio>
<div class="info">
<div class="name">
<p id="qwewq-1">Turntable</p>
</div>
<div class="singer">
<p>Adam M.</p>
</div>
</div>
<div class="d-flex flex-row justify-content-around justify-content-xl-end align-items-xl-center audioBtns">
<p class="timestamp" style="font-size: 20px;margin-bottom: 0px;">00:00</p>
</div>
<div data-toggle="tooltip" id="progressBar-1" class="progress"></div>
</div>
</div>
</div>
Run the operation only on selected container using jQuery eq() method
Main changes:
if (aud.paused) {
aud.play();
aud.loop = false;
$(".play-pause").eq(val - 1).removeClass("icon-play"); // added .eq(val)
$(".play-pause").eq(val - 1).addClass("icon-stop");
} else {
aud.pause();
$(".play-pause").eq(val - 1).removeClass("icon-stop");
$(".play-pause").eq(val - 1).addClass("icon-play");
}
// -----------
$(".progress").eq(val - 1).css("width", (aud.currentTime / aud.duration) * 100 + "%");
// -----------
$(".timestamp").eq(val - 1).text(mins + ":" + secs);
Working Example Below :
function playAudio(val) {
var aud = $("audio")[val - 1];
if (aud.paused) {
aud.play();
aud.loop = false;
$(".play-pause").eq(val - 1).removeClass("icon-play");
$(".play-pause").eq(val - 1).addClass("icon-stop");
} else {
aud.pause();
$(".play-pause").eq(val - 1).removeClass("icon-stop");
$(".play-pause").eq(val - 1).addClass("icon-play");
}
aud.ontimeupdate = function() {
$(".progress").eq(val - 1)
.css("width", (aud.currentTime / aud.duration) * 100 + "%");
var mins = Math.floor(aud.currentTime / 60);
if (mins < 10) {
mins = "0" + String(mins);
}
var secs = Math.floor(aud.currentTime % 60);
if (secs < 10) {
secs = "0" + String(secs);
}
$(".timestamp").eq(val - 1)
.text(mins + ":" + secs);
};
}
.player {
position: relative;
display: flex;
border-radius: 0px;
padding: 5 16px;
}
.player .info {
display: flex;
flex-flow: column nowrap;
justify-content: center;
width: 50%;
padding: 0 16px;
}
.player .info .name {
font-size: 15px;
font-weight: 700;
}
.player .info .singer {
font-size: 12px;
}
.player .audioBtns {
width: 50%;
/*align-items: center;*/
padding: 0 16px;
}
.player .audioBtns div:nth-child(1) {
font-size: 30px;
}
.player .audioBtns div:nth-child(2),
.player .audioBtns div:nth-child(3) {
font-size: 18px;
}
.player .progress {
position: absolute;
height: 5px;
left: 0;
bottom: 0;
background-color: #f8f9fa;
border-radius: 0px;
}
.icon-loop {
content: url("loop.svg");
width: 20px;
height: 20px;
display: block;
}
.icon-play:before {
content: url("https://image.flaticon.com/icons/svg/860/860768.svg");
width: 30px;
height: 45px;
display: block;
}
.icon-stop:before {
content: url("https://image.flaticon.com/icons/svg/633/633940.svg");
width: 30px !important;
height: 40px !important;
display: block;
}
.playBtn {
padding: 0 16px;
}
.activeOverlay {
filter: invert(42%) sepia(11%) saturate(1216%) hue-rotate(279deg) brightness(88%) contrast(85%);
}
.audioContainer {
background-color: #d3d3d3;
padding: 2% 2% !important;
}
.audioContainer:not(:last-child) {
margin-bottom: 3%;
}
.audioContainerActive {
background-color: #855b6f !important;
color: #f8f9fa !important;
}
.IconActive {
filter: invert(92%) sepia(17%) saturate(3434%) hue-rotate(186deg) brightness(127%) contrast(95%);
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- First Audio Container. OnClick on Line 5 -->
<div class="row no-gutters d-flex flex-column col-12">
<div class="col d-flex flex-column justify-content-xl-center audioContainer">
<div class="player">
<div class="d-flex flex-row align-items-xl-center playBtn" onclick="playAudio(1)"><i class="fas fa-pause iconfont play-pause icon-play"></i></div><audio src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3" type="audio/mpeg"></audio>
<div class="info">
<div class="name">
<p id="qwewq">By The Shell</p>
</div>
<div class="singer">
<p>Adam M.</p>
</div>
</div>
<div class="d-flex flex-row justify-content-around justify-content-xl-end align-items-xl-center audioBtns">
<p class="timestamp" style="font-size: 20px;margin-bottom: 0px;">00:00</p>
</div>
<div data-toggle="tooltip" id="progressBar" class="progress"></div>
</div>
</div>
<!-- Second Audio Container. OnClick on Line 25 -->
<div class="col d-flex flex-column justify-content-xl-center audioContainer">
<div class="player">
<div class="d-flex flex-row align-items-xl-center playBtn" onclick="playAudio(2)"><i class="fas fa-pause iconfont play-pause icon-play"></i></div><audio src="https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3" type="audio/mpeg"></audio>
<div class="info">
<div class="name">
<p id="qwewq-1">Turntable</p>
</div>
<div class="singer">
<p>Adam M.</p>
</div>
</div>
<div class="d-flex flex-row justify-content-around justify-content-xl-end align-items-xl-center audioBtns">
<p class="timestamp" style="font-size: 20px;margin-bottom: 0px;">00:00</p>
</div>
<div data-toggle="tooltip" id="progressBar-1" class="progress"></div>
</div>
</div>
</div>
jQuery eq() method
The jQuery eq() method is used to get an element with a specific index of the selected HTML element. You can give either positive or negative integer value as index. The index of the first element of the matched element is 0. If we use selector.eq(-1), it will return the last element and selector.eq(0) will return the first element in the matched set of elements.
syntax - selector.eq(index)
Reference : click_here

jquery adds .active class to all elements when page is loaded

I'm creating a jquery webplayer.
My problem is when the page loads the song titles in the #playlist have a .active class. And further more the <div id="audio-info"> part displays data for all songs in the playlist.
But when I select a song from the playlist, everything is working as it should, the active song takes the .active class and the #audio-info only displays info for the active song.
I'm not sure why this is not working correctly when the page loads.
Can someone here take a look at the code and guide me?
The bug is probably around this chunk of code in the js $('#playlist li').removeClass('active');
element.addClass('active');
here is a snippet
$(document).ready(function() {
var audio;
//Hide pause
$('#pause').hide();
initAudio($('#playlist li:first-child'));
function initAudio(element) {
var song = element.attr('song');
var title = element.text();
var artist = element.attr('artist');
// Audio Object
audio = new Audio('media/' + song);
//insert audio info
$('.artist').text(artist);
$('.title').text(title);
console.log(audio);
$('#playlist li').removeClass('active');
element.addClass('active');
}
// play button
$('#play').click(function() {
audio.play();
$('#play').hide();
$('#pause').show();
showDuration();
});
//Pause button
$('#pause').click(function() {
audio.pause();
$('#play').show();
$('#pause').hide();
});
//Next button
$('#next').click(function() {
audio.pause();
var next = $('#playlist li.active').next();
if (next.length == 0) {
next = $('#playlist li:first-child');
}
initAudio(next);
audio.play();
showDuration();
});
$('#playlist li').click(function() {
audio.pause();
initAudio($(this));
$('#play').hide();
$('#pause').show();
audio.play();
showDuration();
});
//volume control
$('#volume').change(function() {
audio.volume = parseFloat(this.value / 100);
console.log(audio.volume);
});
//Time/showDuration
function showDuration() {
$(audio).bind('timeupdate', function() {
//Get Hours and minutes
var s = parseInt(audio.currentTime % 60);
var m = parseInt(audio.currentTime / 60) % 60;
if (s < 10) {
s = '0' + s;
}
$('#duration').html(m + ':' + s);
var value = 0;
if (audio.currentTime > 0) {
value = Math.floor((100 / audio.duration) * audio.currentTime);
}
$('#progress').css('width', value + '%');
});
};
var promise = audio.play();
if (promise !== undefined) {
promise.then(_ => {
// Autoplay started!
}).catch(error => {
// Autoplay was prevented.
// Show a "Play" button so that user can start playback.
});
}
});
/*************Player ******/
.clearfix {
clear: both;
}
.audio-player {
margin-top: 20px;
margin-bottom: 20px;
}
.progressbar-container {
display: inline-flex;
width: 100px;
margin: 0;
position: relative;
top: 7px;
}
.progress-bar {
background-color: #c2002d !important;
}
#audio-info {
text-align: center;
background-color: lightgrey;
color: #c2002d;
}
input#volume {
width: 95%;
margin-left: 2%;
-webkit-appearance: none !important;
background: #ccc;
height: 1px;
margin-bottom: 20px;
}
input#volume::-webkit-slider-thumb {
-webkit-appearance: none !important;
background: url(/uploads/images/player//knobred.png) no-repeat center center;
background-size: 10px 10px;
width: 10px;
height: 10px;
cursor: pointer;
}
#buttons {
width: 15%;
display: block;
/*margin: 15px auto;*/
/*margin-left: 23px;*/
/* overflow: auto;*/
}
button#play {
width: 20px;
height: 20px;
background: url(/uploads/images/player/play.svg) no-repeat center center;
background-size: 15px 15px;
border: none;
}
button#pause {
width: 20px;
height: 20px;
background: url(/uploads/images/player/pause.svg) no-repeat center center;
background-size: 15px 15px;
border: none;
}
/*button#prev{
width: 20px;
height: 20px;
background: url(../images/rev.svg) no-repeat center center;
background-size: 15px 15px;
}*/
#tracker {
position: relative;
width: 5%;
}
#playlist {
padding-inline-start: 0px !important;
}
#playlist li {
list-style: none;
cursor: pointer;
}
.active {
color: #c2002d;
}
#playlist>li>img {
height: 15px;
float: right;
margin-top: 5px;
cursor: pointer;
}
a>img {
height: 15px;
float: right;
margin-top: 5px;
cursor: pointer;
display: inline-block;
}
/*.info-dot{
height: 15px;
background: url(../images/player/info.svg) no-repeat center center;
cursor: pointer;
display: inline-block;
}*/
/************Player ends *********/
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-md-9">
sfs
</div>
<div class="col-md-3">
<div class="audio-player">
<div id="audio-info">
<span class="artist"></span> - <span class="title"></span>
</div>
<input id="volume" type="range" min="0" max="100" value="50">
<br>
<div id="buttons">
<span>
<!-- <button id="prev"> </button> -->
<button id="play"></button>
<button id="pause"></button>
<!-- <button id="stop"></button>-->
<!-- <button id="next"> >> </button>-->
</span>
</div>
<div class="clearfix"></div>
<div id="tracker">
<div id="progress-bar" class="progress">
<span id="progress" class="progress-bar" role="progressbar"></span>
</div>
<span id="duration"></span>
</div>
<div class="clearfix"></div>
<ul id="playlist" class="hidden">
<div class="d-flex flex-row">
<div class="col-md-9">
<li class="active" song="somesong.mp3" cover="cover1.jpg" artist="someartist">somesong.mp3</li>
</div>
<div class="col-md-3">
<a data-toggle="popover" title="Popover Header" data-placement="left" data-content="Some content inside the popover">
<img src="/images/player/info.svg"></a>
</div>
</div>
<div class="d-flex flex-row">
<div class="col-md-9">
<li class="active" song="song2.mp3" cover="cover1.jpg" artist="someartist">song2.mp3</li>
</div>
<div class="col-md-3">
<a data-toggle="popover" title="Popover Header" data-placement="left" data-content="Some content inside the popover">
<img src="/images/player/info.svg"></a>
</div>
</div>
<div class="d-flex flex-row">
<div class="col-md-9">
<li class="active" song="song3.mp3" cover="cover1.jpg" artist="someartist">song3.mp3</li>
</div>
<div class="col-md-3">
<a data-toggle="popover" title="Popover Header" data-placement="left" data-content="Some content inside the popover">
<img src="/images/player/info.svg"></a>
</div>
</div>
</ul>
</div>
</div>
</div>
<!-- row -->
</div>
<!--Container -->
You currently use li:first-child, but since each li has a different parent, they are all first-child of their respective parents. Use #playlist > div:first-child li
$(document).ready(function() {
var audio;
//Hide pause
$('#pause').hide();
initAudio($('#playlist > div:first-child li'));
function initAudio(element) {
var song = element.attr('song');
var title = element.text();
var artist = element.attr('artist');
// Audio Object
audio = new Audio('media/' + song);
//insert audio info
$('.artist').text(artist);
$('.title').text(title);
console.log(audio);
$('#playlist li').removeClass('active');
element.addClass('active');
}
// play button
$('#play').click(function() {
audio.play();
$('#play').hide();
$('#pause').show();
showDuration();
});
//Pause button
$('#pause').click(function() {
audio.pause();
$('#play').show();
$('#pause').hide();
});
//Next button
$('#next').click(function() {
audio.pause();
var next = $('#playlist li.active').next();
if (next.length == 0) {
next = $('#playlist li:first-child');
}
initAudio(next);
audio.play();
showDuration();
});
$('#playlist li').click(function() {
audio.pause();
initAudio($(this));
$('#play').hide();
$('#pause').show();
audio.play();
showDuration();
});
//volume control
$('#volume').change(function() {
audio.volume = parseFloat(this.value / 100);
console.log(audio.volume);
});
//Time/showDuration
function showDuration() {
$(audio).bind('timeupdate', function() {
//Get Hours and minutes
var s = parseInt(audio.currentTime % 60);
var m = parseInt(audio.currentTime / 60) % 60;
if (s < 10) {
s = '0' + s;
}
$('#duration').html(m + ':' + s);
var value = 0;
if (audio.currentTime > 0) {
value = Math.floor((100 / audio.duration) * audio.currentTime);
}
$('#progress').css('width', value + '%');
});
};
var promise = audio.play();
if (promise !== undefined) {
promise.then(_ => {
// Autoplay started!
}).catch(error => {
// Autoplay was prevented.
// Show a "Play" button so that user can start playback.
});
}
});
/*************Player ******/
.clearfix {
clear: both;
}
.audio-player {
margin-top: 20px;
margin-bottom: 20px;
}
.progressbar-container {
display: inline-flex;
width: 100px;
margin: 0;
position: relative;
top: 7px;
}
.progress-bar {
background-color: #c2002d !important;
}
#audio-info {
text-align: center;
background-color: lightgrey;
color: #c2002d;
}
input#volume {
width: 95%;
margin-left: 2%;
-webkit-appearance: none !important;
background: #ccc;
height: 1px;
margin-bottom: 20px;
}
input#volume::-webkit-slider-thumb {
-webkit-appearance: none !important;
background: url(/uploads/images/player//knobred.png) no-repeat center center;
background-size: 10px 10px;
width: 10px;
height: 10px;
cursor: pointer;
}
#buttons {
width: 15%;
display: block;
/*margin: 15px auto;*/
/*margin-left: 23px;*/
/* overflow: auto;*/
}
button#play {
width: 20px;
height: 20px;
background: url(/uploads/images/player/play.svg) no-repeat center center;
background-size: 15px 15px;
border: none;
}
button#pause {
width: 20px;
height: 20px;
background: url(/uploads/images/player/pause.svg) no-repeat center center;
background-size: 15px 15px;
border: none;
}
/*button#prev{
width: 20px;
height: 20px;
background: url(../images/rev.svg) no-repeat center center;
background-size: 15px 15px;
}*/
#tracker {
position: relative;
width: 5%;
}
#playlist {
padding-inline-start: 0px !important;
}
#playlist li {
list-style: none;
cursor: pointer;
}
.active {
color: #c2002d;
}
#playlist>li>img {
height: 15px;
float: right;
margin-top: 5px;
cursor: pointer;
}
a>img {
height: 15px;
float: right;
margin-top: 5px;
cursor: pointer;
display: inline-block;
}
/*.info-dot{
height: 15px;
background: url(../images/player/info.svg) no-repeat center center;
cursor: pointer;
display: inline-block;
}*/
/************Player ends *********/
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-md-9">
sfs
</div>
<div class="col-md-3">
<div class="audio-player">
<div id="audio-info">
<span class="artist"></span> - <span class="title"></span>
</div>
<input id="volume" type="range" min="0" max="100" value="50">
<br>
<div id="buttons">
<span>
<!-- <button id="prev"> </button> -->
<button id="play"></button>
<button id="pause"></button>
<!-- <button id="stop"></button>-->
<!-- <button id="next"> >> </button>-->
</span>
</div>
<div class="clearfix"></div>
<div id="tracker">
<div id="progress-bar" class="progress">
<span id="progress" class="progress-bar" role="progressbar"></span>
</div>
<span id="duration"></span>
</div>
<div class="clearfix"></div>
<ul id="playlist" class="hidden">
<div class="d-flex flex-row">
<div class="col-md-9">
<li class="active" song="somesong.mp3" cover="cover1.jpg" artist="someartist">somesong.mp3</li>
</div>
<div class="col-md-3">
<a data-toggle="popover" title="Popover Header" data-placement="left" data-content="Some content inside the popover">
<img src="/images/player/info.svg"></a>
</div>
</div>
<div class="d-flex flex-row">
<div class="col-md-9">
<li class="active" song="song2.mp3" cover="cover1.jpg" artist="someartist">song2.mp3</li>
</div>
<div class="col-md-3">
<a data-toggle="popover" title="Popover Header" data-placement="left" data-content="Some content inside the popover">
<img src="/images/player/info.svg"></a>
</div>
</div>
<div class="d-flex flex-row">
<div class="col-md-9">
<li class="active" song="song3.mp3" cover="cover1.jpg" artist="someartist">song3.mp3</li>
</div>
<div class="col-md-3">
<a data-toggle="popover" title="Popover Header" data-placement="left" data-content="Some content inside the popover">
<img src="/images/player/info.svg"></a>
</div>
</div>
</ul>
</div>
</div>
</div>
<!-- row -->
</div>
<!--Container -->

How can i filter a list of divs when 3 or more checkboxes are checked using jquery or even plain javascript?

Based on a previous question of mine i want to filter a list of divs by different combinations based on the existence of specific div elements.
In the below example i use 3 checkboxes "Card", "Paypal", "Show only open stores" to filter the list. As it is now it works for the "Card" & "Paypal" checkboxes but if you try to check also the "Show only open stores" checkbox it messing it up. How can i fix that?
Here's the code:
var checkboxArea = document.querySelector('.filter-area')
var storeBlocks = Array.from(document.querySelectorAll('.store-block'))
var byCard = document.getElementById('by-card')
var byPaypal = document.getElementById('by-paypal')
var byOpen = document.getElementById('by-open')
var cardBlocks = storeBlocks.filter(function(block) {
return block.querySelector('.card-available')
})
var payPalBlocks = storeBlocks.filter(function(block) {
return block.querySelector('.paypal-available')
})
var openStoreBlocks = storeBlocks.filter(function(block) {
return block.querySelector('.close-small-tag')
})
checkboxArea.addEventListener('change', function(e) {
switch (true) {
case byCard.checked && byPaypal.checked:
storeBlocks.forEach(function(block) {
block.classList.remove('hide-me')
})
break
case byCard.checked:
cardBlocks.forEach(function(block) {
block.classList.remove('hide-me')
})
payPalBlocks.forEach(function(block) {
block.classList.add('hide-me')
})
break
case byPaypal.checked:
cardBlocks.forEach(function(block) {
block.classList.add('hide-me')
})
payPalBlocks.forEach(function(block) {
block.classList.remove('hide-me')
})
break
case byOpen.checked:
openStoreBlocks.forEach(function(block) {
block.classList.toggle('hide-me')
})
break
default:
payPalBlocks.concat(cardBlocks).forEach(function(block) {
block.classList.remove('hide-me')
})
}
})
.close-small-tag,
.open-small-tag {
position: absolute;
left: 130px;
top: 5px;
font-size: 11px;
font-weight: bold;
color: brown;
}
.search-area {
margin-bottom: 10px;
}
.storesList {
margin-top: 20px;
}
#count {
display: inline-block;
}
.store-block {
width: 80%;
margin-bottom: 10px;
padding: 5px;
background: #e5e5e5;
position: relative;
overflow: hidden;
}
.rating {
position: absolute;
right: 70px;
top: 3px;
}
.minorder {
position: absolute;
right: 180px;
top: 3px;
}
.paypal-available,
.card-available {
position: absolute;
right: 10px;
top: 5px;
font-size: 11px;
font-weight: bold;
color: blue;
}
.right {
float: right;
}
.left {
float: left;
}
.hide-me {
display: none;
}
.filter-area {
margin-bottom: 20px;
overflow: hidden;
}
.inputRadioGroup {
float: left;
margin-right: 20px;
font-weight: bold;
font-size: 12px;
text-transform: uppercase;
}
<div class="filter-area">
<div class=" inputRadioGroup">
<input type="checkbox" id="by-card">
<label for="by-card">Card</label>
</div>
<div class=" inputRadioGroup">
<input type="checkbox" id="by-paypal">
<label for="by-paypal">Paypal</label>
</div>
<div class=" inputRadioGroup">
<input type="checkbox" id="by-open">
<label for="by-open">SHOW ONLY OPEN STORES</label>
</div>
</div>
<div class="storesList">
<div class="store-block">
<div class="store-name">Apple Store</div>
<div class="rating">&bigstar; 4.5</div>
<div class="open-small-tag">OPEN</div>
<div class="minorder">100 €</div>
<div class="store-payment-options">
<div class="card-available">CARD</div>
</div>
</div>
<div class="store-block">
<div class="store-name">Nokia Store</div>
<div class="rating">&bigstar; 3.8</div>
<div class="open-small-tag">OPEN</div>
<div class="minorder">250 €</div>
<div class="store-payment-options">
<div class="paypal-available">PAYPAL</div>
</div>
</div>
<div class="store-block">
<div class="store-name">Samsung Store</div>
<div class="rating">&bigstar; 4.0</div>
<div class="close-small-tag">CLOSE</div>
<div class="minorder">25 €</div>
<div class="store-payment-options">
<div class="card-available">CARD</div>
</div>
</div>
<div class="store-block">
<div class="store-name">Linux Store</div>
<div class="rating">&bigstar; 4.9</div>
<div class="close-small-tag">CLOSE</div>
<div class="minorder">50 €</div>
<div class="store-payment-options">
<div class="paypal-available">PAYPAL</div>
</div>
</div>
</div>

Categories