(JavaScript) How to Add Prev and Next Button to Tabs? - javascript

Hope you all have a nice day and Happy Weekend!
I want to ask about adding prev and next button in my Tabs. I already add it, with some JavaScript that referenced to this https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_slideshow.
I know it's kind of weird to reference tab with the carousel but, I think that the principle is the same. But in my code, i don't know how to code it. I'm so sorry because I'm very noob in JavaScript. So, here's my attempt :
//Add & remove class tab, contents, & menu on click
window.addEventListener('DOMContentLoaded', ()=> {
let tabs = document.querySelectorAll('.tab');
let content = document.querySelectorAll('.content');
let prev = document.querySelector('.previous');
let next = document.querySelector('.next');
let firstTab = function(tabs) {tabs.classList.add('tab-active')};
let firstContent = function(content) {content.classList.add('content-active')};
firstTab(tabs[0]);
firstContent(content[0]);
for (let i = 0; i < tabs.length; i++) {
tabs[i].addEventListener('click', () => tabClick(i));
}
prev.addEventListener('click', (i) => tabClick(i - 1));
next.addEventListener('click', (i) => tabClick(i + 1));
function tabClick(currentTab) {
removeActive();
//Add Active Class
tabs[currentTab].classList.add('tab-active');
content[currentTab].classList.add('content-active');
}
function removeActive() {
for (let i = 0; i < tabs.length; i++) {
//Remove Active Class
content[i].classList.remove('content-active');
content[i].classList.add('content-show');
setTimeout(function() {
content[i].classList.remove('content-show');
},1500);
tabs[i].classList.remove('tab-active');
}
}
})
/* WHOLE CONTAINER */
.container {
width: 96vw;
height: 96vh;
}
/* TABS */
.tabs {
display: flex;
height: 50px;
overflow: hidden;
align-items: center;
justify-content: center;
width: 100%;
}
.tab {
font-size: 14px;
padding: 5px 10px;
cursor: pointer;
letter-spacing: 2px;
}
#red.tab-active {background-color: rgb(245, 66, 66);}
#blue.tab-active {background-color: rgb(66, 135, 245);}
#yellow.tab-active {background-color: rgb(245, 215, 66);}
#green.tab-active {background-color: rgb(56, 235, 98);}
#cyan.tab-active {background-color: rgb(79, 247, 219);}
/* TAB CONTENTS */
.contents {
width: 100%;
margin-top: 5px;
height: 80%;
}
.content {
width: 96%;
height: 80%;
display: none;
padding: 0;
margin: 0;
border: none;
position: absolute;
}
.content-show {
display: flex;
animation-name: fade-out;
animation-duration: 2.5s;
}
#keyframes fade-out {
0% {
opacity: 1;
display: flex;
}
99% {
opacity: 0;
display: flex;
}
100% {
opacity: 0;
display: none;
}
}
.content-active {
display: flex;
border: none;
justify-content: center;
animation-name: fade-in;
animation-duration: 2.5s;
}
#keyframes fade-in {
0% {
display: none;
opacity: 0;
}
1% {
display: block;
opacity: 0.01;
}
100%{
display: block;
opacity: 1;
}
}
#red.content-active {background-color: rgb(245, 66, 66);}
#blue.content-active {background-color: rgb(66, 135, 245);}
#yellow.content-active {background-color: rgb(245, 215, 66);}
#green.content-active {background-color: rgb(56, 235, 98);}
#cyan.content-active {background-color: rgb(79, 247, 219);}
/* BUTTON PREVIOUS NEXT */
.button {
position: absolute;
top: 49%;
z-index: 4;
}
.previous, .next {
margin: 5px 10px;
letter-spacing: 2px;
background-color: white;
font-size: 14px;
text-align: center;
padding: 5px;
cursor: pointer;
}
<div class="container">
<div class="tabs">
<div id="red" class="tab">RED</div>
<div id="blue" class="tab">BLUE</div>
<div id="yellow" class="tab">YELLOW</div>
<div id="green" class="tab">GREEN</div>
<div id="cyan" class="tab">CYAN</div>
</div>
<div class="contents">
<div id="red" class="content"></div>
<div id="blue" class="content"></div>
<div id="yellow" class="content"></div>
<div id="green" class="content"></div>
<div id="cyan" class="content"></div>
</div>
<div class="button">
<div class="previous">PREV</div>
<div class="next">NEXT</div>
</div>
</div>
Please help me to solve this code guys. Thanks a lot.

The only problem that you are facing is when you click on the prev or next button you have passed the argument i in tabClick function but i is not the index rather it is the property of click event.
Here's what you have done 👇
prev.addEventListener('click', (i) => tabClick(i - 1));
next.addEventListener('click', (i) => tabClick(i + 1));
Here i represents the property of click and the element you have clicked on so it does not give the index.
What you can rather do is:
Create a global variable called activeTab and set the default to 0.
Inside tabClick fucntion set activeTab to currentTab as activeTab = currentTab
Now, inside prev function write tabClick(actie - 1)
Follow the same for next function.
Here's my code 👇
//Add & remove class tab, contents, & menu on click
window.addEventListener('DOMContentLoaded', ()=> {
let tabs = document.querySelectorAll('.tab');
let content = document.querySelectorAll('.content');
let prev = document.querySelector('.previous');
let next = document.querySelector('.next');
let firstTab = function(tabs) {tabs.classList.add('tab-active')};
let firstContent = function(content) {content.classList.add('content-active')};
let actieTab = 0;
firstTab(tabs[0]);
firstContent(content[0]);
for (let i = 0; i < tabs.length; i++) {
tabs[i].addEventListener('click', () => tabClick(i));
}
prev.addEventListener('click', () => tabClick(activeTab - 1));
next.addEventListener('click', () => tabClick(activeTab + 1));
function tabClick(currentTab) {
removeActive();
//Add Active Class
tabs[currentTab].classList.add('tab-active');
content[currentTab].classList.add('content-active');
activeTab = currentTab
}
function removeActive() {
for (let i = 0; i < tabs.length; i++) {
//Remove Active Class
content[i].classList.remove('content-active');
content[i].classList.add('content-show');
setTimeout(function() {
content[i].classList.remove('content-show');
},1500);
tabs[i].classList.remove('tab-active');
}
}
})

For the issue that no class is selected after the end of the array, you can do this 👇
Add a codition to check if the activeTab is at the end of the array.
If it is, we set activeTab back to 0 and call the function tabClick and pass the activeTab in it
If not, in else we'll do the same thing which we were doing before
Follow the same for prev button
Code example
prev.addEventListener("click", (i) => {
if (activeTab === 0) {
activeTab = tabs.length - 1;
tabClick(activeTab);
} else {
tabClick(activeTab - 1);
}
});
next.addEventListener("click", (i) => {
if (activeTab >= tabs.length - 1) {
activeTab = 0;
tabClick(activeTab);
} else {
tabClick(activeTab + 1);
}
});

Related

Why do I keep getting 4 slides when there are only 3 div elements?

I created a slideshow with 3 slides but for some reason, it keeps adding an additional slide
const slideshow = document.getElementById("slideshow");
const slides = slideshow.children;
let currentSlide = 0;
function goToSlide(n) {
slides[currentSlide].classList.remove("active");
currentSlide = (n + slides.length) % slides.length;
slides[currentSlide].classList.add("active");
updateSlideshowCounter();
}
function nextSlide() {
goToSlide(currentSlide + 1);
}
function prevSlide() {
goToSlide(currentSlide - 1);
}
function updateSlideshowCounter() {
const slideshowCounter = document.getElementById("slideshow-counter");
slideshowCounter.textContent = `${currentSlide + 1} / ${slides.length}`;
}
const prevButton = document.getElementById("prev-button");
prevButton.addEventListener("click", prevSlide);
const nextButton = document.getElementById("next-button");
nextButton.addEventListener("click", nextSlide);
updateSlideshowCounter();
#slideshow {
position: relative;
text-align: center;
width: 400px;
height: 300px;
border: 1px black solid;
}
.slide {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 1s;
}
.slide.active {
opacity: 1;
}
#slideshow-controls {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
align-items: center;
}
#prev-button,
#next-button {
padding: 10px 20px;
border: none;
background-color: #333;
color: #fff;
cursor: pointer;
}
#prev-button {
margin-right: 20px;
}
#next-button {
margin-left: 20px;
}
#slideshow-counter {
margin: 0 20px;
}
<div id="slideshow">
<div class="slide">Slide 1</div>
<div class="slide">Slide 2</div>
<div class="slide">Slide 3</div>
<div id="slideshow-controls">
<button id="prev-button">Prev</button>
<span id="slideshow-counter"></span>
<button id="next-button">Next</button>
</div>
</div>
Can someone tell me what my mistake is and how I can get 3 slides in the output instead of 4.
You're defining your slides with the statement const slides = slideshow.children;. Your slideshow has a total of 4 direct children, so the counter is technically correct (see slide 1, slide 2, slide 3, and slideshow-controls).
One approach to get just the slides you want is to use const slides = document.getElementsByClassName("slide"). I hope this helps!
The problem is your slides variable is not assigned to the correct list of elements, as the previous answer said, you should replace slideshow.children with either document.getElementsByClassName('slide') or document.querySelectorAll('.slide'), use any of the two.
By using slideshow.children, you're not getting .slide classes, you're getting all children of #slideshow.
So, your variable in line 67, should be as the following:
const slides = document.querySelectorAll('.slide');
or
const slides = document.getElementsByClassName('.slide');
You should keep slideshow controls out of your slideshow div. I am attaching Code Below. Run it and check.
const slideshow = document.getElementById("slideshow");
const slides = slideshow.children;
let currentSlide = 0;
function goToSlide(n) {
slides[currentSlide].classList.remove("active");
currentSlide = (n + slides.length) % slides.length;
slides[currentSlide].classList.add("active");
updateSlideshowCounter();
}
function nextSlide() {
goToSlide(currentSlide + 1);
}
function prevSlide() {
goToSlide(currentSlide - 1);
}
function updateSlideshowCounter() {
const slideshowCounter = document.getElementById("slideshow-counter");
slideshowCounter.textContent = `${currentSlide + 1} / ${slides.length}`;
}
const prevButton = document.getElementById("prev-button");
prevButton.addEventListener("click", prevSlide);
const nextButton = document.getElementById("next-button");
nextButton.addEventListener("click", nextSlide);
updateSlideshowCounter();
#slideshowbox {
position: relative;
width: 400px;
height: 300px;
}
#slideshow {
position: relative;
text-align: center;
width: 400px;
height: 300px;
border: 1px black solid;
}
.slide {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 1s;
}
.slide.active {
opacity: 1;
}
#slideshow-controls {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
align-items: center;
}
#prev-button,
#next-button {
padding: 10px 20px;
border: none;
background-color: #333;
color: #fff;
cursor: pointer;
}
#prev-button {
margin-right: 20px;
}
#next-button {
margin-left: 20px;
}
#slideshow-counter {
margin: 0 20px;
}
<div id="slideshowbox">
<div id="slideshow">
<div class="slide">Slide 1</div>
<div class="slide">Slide 2</div>
<div class="slide">Slide 3</div>
</div>
<div id="slideshow-controls">
<button id="prev-button">Prev</button>
<span id="slideshow-counter"></span>
<button id="next-button">Next</button>
</div>
</div>
Your slideshow div childs is throwing 4 because your 4th div is slideshow-controls. You may want to add -1 to the counter or redifine the way you make your div. Best of luck!

change background colour of div on carousel

I'm trying to get to grips with javascript, and have followed a tutorial for a simple image slider. I'm trying to add to it and have the background fade to different colours as the slides move. I've managed to figure it out with the right and left arrows (not sure on best practise), but I can't seem to get it right when selecting the indicators. Can anyone advise on a solution?
Thanks in advance.
const left = document.querySelector('.left');
const right = document.querySelector('.right');
const slider = document.querySelector('.carousel__slider');
const indicatorParent = document.querySelector('.carousel__controls ol');
const indicators = document.querySelectorAll('.carousel__controls li');
index = 0;
var background = 1;
function indicatorBg(val){
var background = val;
changeBg();
}
indicators.forEach((indicator, i) => {
indicator.addEventListener('click', () => {
document.querySelector('.carousel__controls .selected').classList.remove('selected');
indicator.classList.add('selected');
slider.style.transform = 'translateX(' + (i) * -25 + '%)';
index = i;
});
});
left.addEventListener('click', function() {
index = (index > 0) ? index -1 : 0;
document.querySelector('.carousel__controls .selected').classList.remove('selected');
indicatorParent.children[index].classList.add('selected');
slider.style.transform = 'translateX(' + (index) * -25 + '%)';
if (background <= 1) {
return false;
} else {
background--;
}
changeBg();
});
right.addEventListener('click', function() {
index = (index < 4 - 1) ? index+1 : 3;
document.querySelector('.carousel__controls .selected').classList.remove('selected');
indicatorParent.children[index].classList.add('selected');
slider.style.transform = 'translateX(' + (index) * -25 + '%)';
if (background >= 4) {
return false;
} else {
background++;
}
changeBg();
});
function changeBg (){
if (background == 1) {
document.getElementById("carousel__track").className = 'slide-1';
} else if (background == 2) {
document.getElementById("carousel__track").className = 'slide-2';
} else if (background == 3) {
document.getElementById("carousel__track").className = 'slide-3';
} else if (background == 4) {
document.getElementById("carousel__track").className = 'slide-4';
}
}
window.onload = changeBg;
.carousel {
height: 80vh;
width: 100%;
margin: 0 auto;
}
#carousel__track {
height: 100%;
position: relative;
overflow: hidden;
}
.background {
background: red;
}
.carousel__slider {
height: 100%;
display: flex;
width: 400%;
transition: all 0.3s;
}
.carousel__slider div {
flex-basis: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.carousel__controls .carousel__arrow {
position: absolute;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
z-index: 8888
}
.carousel__controls .carousel__arrow i {
font-size: 2.6rem;
}
.carousel__arrow.left {
left: 1em;
}
.carousel__arrow.right {
right: 1em;
}
.carousel__controls ol {
position: absolute;
bottom: 15%;
left: 50%;
transform: translateX(-50%);
list-style: none;
display: flex;
margin: 0;
padding: 0;
}
.carousel__controls ol li {
width: 14px;
height: 14px;
border-radius: 50px;
margin: .5em;
padding: 0;
background: white;
transform: scale(.6);
cursor: pointer;
}
.carousel__controls ol li.selected {
background: black;
transform: scale(1);
transition: all .2s;
transition-delay: .3s;
}
.slide-1 {
background: pink;
transition: all 0.4s;
}
.slide-2 {
background: coral;
transition: all 0.4s;
}
.slide-3 {
background: green;
transition: all 0.4s;
}
.slide-4 {
background: orange;
transition: all 0.4s;
}
<section class="carousel">
<div id="carousel__track">
<div class="carousel__slider">
<div>Slide 1</div>
<div>Slide 2</div>
<div>Slide 3</div>
<div>Slide 4</div>
</div>
<div id="left" class="carousel__controls"><span class="carousel__arrow left"><</span> <span id="right" class="carousel__arrow right">></span>
<ol>
<li value="1" onclick="indicatorBg(this.value)" class="selected"></li>
<li value="2" onclick="indicatorBg(this.value)"></li>
<li value="3" onclick="indicatorBg(this.value)"></li>
<li value="4" onclick="indicatorBg(this.value)"></li>
</ol>
</div>
</div>
</section>
You forgot to change the background inside the click event handler of the indicators.
indicators.forEach((indicator, i) => {
indicator.addEventListener('click', () => {
document.querySelector('.carousel__controls .selected').classList.remove('selected');
indicator.classList.add('selected');
slider.style.transform = 'translateX(' + (i) * -25 + '%)';
index = i;
background = index + 1;
changeBg();
});
});
As far as best practice goes, I typically use class names for CSS and IDs for JavaScript. Personally, I wouldn't recommend you worry about best practices at this stage, but instead, focus on getting the code working and understanding what's going on line-by-line.
There is a lot of solutions, but the simplest solution that I advice is to use odd and even numbers to style the divs in the carousel (meaning that eg. first is green second is orange third is green and so on...
.carousel__slider div:nth-child(2n) /*Selects even numbered elements*/
.carousel__slider div:nth-child(2n+1) /*Selects odd numbered elements*/
Check out the snippet
const left = document.querySelector('.left');
const right = document.querySelector('.right');
const slider = document.querySelector('.carousel__slider');
const indicatorParent = document.querySelector('.carousel__controls ol');
const indicators = document.querySelectorAll('.carousel__controls li');
index = 0;
//var background = 1;
//function indicatorBg(val){
// var background = val;
// changeBg();
//}
indicators.forEach((indicator, i) => {
indicator.addEventListener('click', () => {
document.querySelector('.carousel__controls .selected').classList.remove('selected');
indicator.classList.add('selected');
slider.style.transform = 'translateX(' + (i) * -25 + '%)';
index = i;
});
});
left.addEventListener('click', function() {
index = (index > 0) ? index -1 : 0;
document.querySelector('.carousel__controls .selected').classList.remove('selected');
indicatorParent.children[index].classList.add('selected');
slider.style.transform = 'translateX(' + (index) * -25 + '%)';
// if (background <= 1) {
// return false;
// } else {
// background--;
// }
// changeBg();
});
right.addEventListener('click', function() {
index = (index < 4 - 1) ? index+1 : 3;
document.querySelector('.carousel__controls .selected').classList.remove('selected');
indicatorParent.children[index].classList.add('selected');
slider.style.transform = 'translateX(' + (index) * -25 + '%)';
// if (background >= 4) {
// return false;
// } else {
// background++;
// }
// changeBg();
});
//function changeBg (){
// if (background == 1) {
// document.getElementById("carousel__track").className = 'slide-1';
// } else if (background == 2) {
// document.getElementById("carousel__track").className = 'slide-2';
// } else if (background == 3) {
// document.getElementById("carousel__track").className = 'slide-3';
// } else if (background == 4) {
// document.getElementById("carousel__track").className = 'slide-4';
// }
//}
//window.onload = changeBg;
.carousel {
height: 80vh;
width: 100%;
margin: 0 auto;
}
#carousel__track {
height: 100%;
position: relative;
overflow: hidden;
}
.background {
background: red;
}
.carousel__slider {
height: 100%;
display: flex;
width: 400%;
transition: all 0.3s;
}
.carousel__slider div {
flex-basis: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.carousel__controls .carousel__arrow {
position: absolute;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
z-index: 8888
}
.carousel__controls .carousel__arrow i {
font-size: 2.6rem;
}
.carousel__arrow.left {
left: 1em;
}
.carousel__arrow.right {
right: 1em;
}
.carousel__controls ol {
position: absolute;
bottom: 15%;
left: 50%;
transform: translateX(-50%);
list-style: none;
display: flex;
margin: 0;
padding: 0;
}
.carousel__controls ol li {
width: 14px;
height: 14px;
border-radius: 50px;
margin: .5em;
padding: 0;
background: white;
transform: scale(.6);
cursor: pointer;
}
.carousel__controls ol li.selected {
background: black;
transform: scale(1);
transition: all .2s;
transition-delay: .3s;
}
/*.slide-1 {
background: pink;
transition: all 0.4s;
}
.slide-2 {
background: coral;
transition: all 0.4s;
}
.slide-3 {
background: green;
transition: all 0.4s;
}
.slide-4 {
background: orange;
transition: all 0.4s;
}*/
.carousel__slider div:nth-child(2n) {
background-color:orange;
}
.carousel__slider div:nth-child(2n+1) {
background-color:green;
}
<section class="carousel">
<div id="carousel__track">
<div class="carousel__slider">
<div>Slide 1</div>
<div>Slide 2</div>
<div>Slide 3</div>
<div>Slide 4</div>
</div>
<div id="left" class="carousel__controls"><span class="carousel__arrow left"><</span> <span id="right" class="carousel__arrow right">></span>
<ol>
<li value="1" class="selected"></li>
<li value="2" ></li>
<li value="3" ></li>
<li value="4" ></li>
</ol>
</div>
</div>
</section>

Why blocked pointer events are fired while timed-out function with no delay is running?

Why after clicking the load button, both buttons load and dummy covered by the loader's overlay still register clicks?
Sometimes when clicking the load button, the loader is not even displayed.
Buttons correctly don't register clicks
if we for example display the loader from the start by commenting the line 5 loader.hide();
add some timeout delay (but I don't want that)
Example (best to run in Full Page mode):
const iterations = 1e3;
const multiplier = 1e9;
const loader = $('.css-loader-fullscreen');
const dummyBtn = $('#dummy');
const loadBtn = $('#load');
loader.hide();
dummyBtn.on('click', () => console.log('dummy clicked'));
loadBtn.on('click', jsHeavyTask);
function calculatePrimes(iterations, multiplier) {
var primes = [];
for (var i = 0; i < iterations; i++) {
var candidate = i * (multiplier * Math.random());
var isPrime = true;
for (var c = 2; c <= Math.sqrt(candidate); ++c) {
if (candidate % c === 0) {
// not prime
isPrime = false;
break;
}
}
if (isPrime) {
primes.push(candidate);
}
}
return primes;
}
function jsHeavyTask(){
console.log('heavy function started');
loader.show();
setTimeout(() => {
const start = performance.now();
calculatePrimes(iterations, multiplier);
const end = performance.now();
loader.hide();
console.log('heavy function ended in '+ (end - start).toFixed() +' ms');
});
}
input {width: 150px}
.css-loader-background {
display: flex;
align-items: center;
justify-content: center;
background-color: white;
border-radius: 10px;
font-size: 12px;
}
.css-loader-fullscreen {
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: 100000;
position: fixed;
background-color: rgba(0, 0, 0, 0.4);
display: flex;
justify-content: center;
align-items: center;
}
.css-loader-fullscreen .css-loader-background {
width: 100px;
height: 100px;
}
.css-loader-animation {
width: 40px;
height: 40px;
border-radius: 50%;
border: 8px solid transparent;
border-top-color: purple;
border-bottom-color: purple;
text-indent: -9999em;
animation: spinner 0.8s ease infinite;
transform: translateZ(0);
}
#-webkit-keyframes spinner {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="css-loader-fullscreen">
<div class="css-loader-background">
<div class="css-loader-animation"></div>
</div>
</div>
<input id="load" type="button" value="load">
<input id="dummy" type="button" value="dummy">
Run times of jsHeavyTask() are different on every machine. For me it's around 5s. You can change iterations and multiplier constants to modify the run time.
There is lot more of weird I observed related to this no delay timed-out calc-heavy function, especially in Webkit, but first I am curious about this one.
as first I would try to call the heavy function differently:
loadBtn.on('click', () => {
loader.show();
jsHeavyTask
});
If that doesn't do the trick, I would try different approach with the show/hide method and use opacity with ponter-events combination for better performance and disabling passing through the clicks.
JavaScript
const loader = $('.css-loader-fullscreen');
const dummyBtn = $('#dummy');
const loadBtn = $('#load');
const content = $('#content');
const cssHidden = 'css-hidden';
const cssLoading = 'css-loading';
loader.addClass(cssHidden);
dummyBtn.on('click', () => console.log('dummy clicked'));
loadBtn.on('click', () => {
content.addClass(cssLoading);
loader.removeClass(cssHidden);
jsHeavyTask
});
function jsHeavyTask(){
console.log('heavy function started');
setTimeout(() => {
for ( var i = 0; i < 2e7; i++){
Math.sqrt(Date.now());
}
loader.addClass(cssHidden);
content.removeClass(cssLoading);
console.log('heavy function ended');
});
}
CSS (only changes)
.css-loader-fullscreen {
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: 100000;
position: fixed;
background-color: rgba(0, 0, 0, 0.4);
display: flex;
justify-content: center;
align-items: center;
opacity: 99.99999;
pointer-events: auto;
}
.css-hidden {
opacity: 0.000001;
pointer-events: none;
}
.css-loading {
pointer-events: none;
}
HTML
<div class="css-loader-fullscreen">
<div class="css-loader-background">
<div class="css-loader-animation"></div>
</div>
</div>
<div id="content">
<input id="load" type="button" value="load">
<input id="dummy" type="button" value="dummy">
</div>
Sometimes when clicking the load button, the loader is not even displayed.
Obviously because of this setTimeout function
setTimeout(() => {
for (var i = 0; i < 2e7; i++) {
Math.sqrt(Date.now());
}
console.log('heavy function ended');
});
The setTimeout makes your code, kind of async, so the inside runs smoothly and with the provided delay. Here, you have almost no delay, it's just a simple timeout that runs instantly, the functions inside as there's little to no delay value.
On the other hand, the for loop has dynamic run times.
var t0 = performance.now();
for (var i = 0; i < 2e7; i++) {
Math.sqrt(Date.now());
}
var t1 = performance.now();
console.log("Took " + (t1 - t0) + " milliseconds.");
So sometimes it runs fast enough and that means that your loader.hide(); runs instantly and hides your overlay and sometimes not so you see the loader.
Why after clicking the load button, both buttons covered by the loader's overlay still register clicks?
I don't know what you mean there but if you mean that you can click as the overlay displays then no, try debugging by not allowing the loaders to go and then click the other button, you'll notice that the click is not registered.
const loader = $('.css-loader-fullscreen');
const dummyBtn = $('#dummy');
const loadBtn = $('#load');
loader.hide();
dummyBtn.on('click', () => console.log('dummy clicked'));
loadBtn.on('click', jsHeavyTask);
function jsHeavyTask(){
console.log('heavy function started');
loader.show();
setTimeout(() => {
for ( var i = 0; i < 2e6; i++){
Math.sqrt(Date.now());
}
// loader.hide();
console.log('heavy function ended');
});
}
input {width: 150px}
.css-loader-background {
display: flex;
align-items: center;
justify-content: center;
background-color: white;
border-radius: 10px;
font-size: 12px;
}
.css-loader-fullscreen {
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: 100000;
position: fixed;
background-color: rgba(0, 0, 0, 0.4);
display: flex;
justify-content: center;
align-items: center;
}
.css-loader-fullscreen .css-loader-background {
width: 100px;
height: 100px;
}
.css-loader-animation {
width: 40px;
height: 40px;
border-radius: 50%;
border: 8px solid transparent;
border-top-color: purple;
border-bottom-color: purple;
text-indent: -9999em;
animation: spinner 0.8s ease infinite;
transform: translateZ(0);
}
#-webkit-keyframes spinner {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="css-loader-fullscreen">
<div class="css-loader-background">
<div class="css-loader-animation"></div>
</div>
</div>
<input id="load" type="button" value="load">
<input id="dummy" type="button" value="dummy">
NOTE: Some of your stated behaviors are inconsistent with the given observations in the questions, I suggest you adequately validate them.
It simply seems that the browser is memorizing all the clicks while the JS calculation is running. But those clicks are not applied to the painted layout existing before AND during the heavy JS calculation. They are applied to the repainted layout which includes changes introduced while the JS calculation was running. So no loader overlay to catch those clicks.
I would expect the clicks to be applied to the original existing layout, when the loader overlay is still displayed.
edit: adding a correct solution below without a need to add some delay
const iterations = 1e3;
const multiplier = 1e9;
const loader = $('.css-loader-fullscreen');
const dummyBtn = $('#dummy');
const loadBtn = $('#load');
loader.hide();
dummyBtn.on('click', () => console.log('dummy clicked'));
loadBtn.on('click', jsHeavyTask);
function calculatePrimes(iterations, multiplier) {
var primes = [];
for (var i = 0; i < iterations; i++) {
var candidate = i * (multiplier * Math.random());
var isPrime = true;
for (var c = 2; c <= Math.sqrt(candidate); ++c) {
if (candidate % c === 0) {
// not prime
isPrime = false;
break;
}
}
if (isPrime) {
primes.push(candidate);
}
}
return primes;
}
function renderLayoutAndRun(f){
window.requestAnimationFrame(() => {
window.requestAnimationFrame(f);
});
};
function jsHeavyTask(){
loader.show();
renderLayoutAndRun(() => {
console.log('heavy function started');
const start = performance.now();
calculatePrimes(iterations, multiplier);
const end = performance.now();
renderLayoutAndRun(() => loader.hide());
console.log('heavy function ended in '+ (end - start).toFixed() +' ms');
});
}
input {width: 150px}
.css-loader-background {
display: flex;
align-items: center;
justify-content: center;
background-color: white;
border-radius: 10px;
font-size: 12px;
}
.css-loader-fullscreen {
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: 100000;
position: fixed;
background-color: rgba(0, 0, 0, 0.4);
display: flex;
justify-content: center;
align-items: center;
}
.css-loader-fullscreen .css-loader-background {
width: 100px;
height: 100px;
}
.css-loader-animation {
width: 40px;
height: 40px;
border-radius: 50%;
border: 8px solid transparent;
border-top-color: purple;
border-bottom-color: purple;
text-indent: -9999em;
animation: spinner 0.8s ease infinite;
transform: translateZ(0);
}
#-webkit-keyframes spinner {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="css-loader-fullscreen">
<div class="css-loader-background">
<div class="css-loader-animation"></div>
</div>
</div>
<input id="load" type="button" value="load">
<input id="dummy" type="button" value="dummy">

When i changed position of functions why doesn't it work with javascript closure?

I'm a new javascript, let me direct to the point. I have heard that we have to avoid global variables as much as we can, so, i learn to use closure for make sure that variables can not access to each other.
I have slideShow function which is on the top and toggleMenu function on the bottom, these functions are work fine in my webpage.
My problems is when i changed position of functions, slideShow function to the bottom and toggleMenu function to the top, my webpage it looks not fine, doesn't work properly
May be there is something that i don't know? or i did something wrong? if any one would give me some advices i would appreciate that, thank you.
Here is original code
var slideShow = (function () {
var slideImages = document.getElementsByClassName("slide");
var leftSide = document.getElementById("arrow-left");
var rightSide = document.getElementById("arrow-right");
var slideBullets = document.getElementsByClassName("bullets");
var current = 0;
function reset() {
for (let i = 0; i < slideImages.length; i++) {
slideImages[i].style.display = 'none';
slideBullets[i].classList.remove("clicked");
}
};
function showImages() {
for (let i = 0; i < slideImages.length; i++) {
slideImages[0].style.display = 'block';
slideBullets[current].classList.add("clicked");
}
};
function arrowSlide() {
leftSide.addEventListener("click", function () {
reset();
if (current === 0) {
current = slideImages.length;
}
slideImages[current - 1].style.display = 'block';
current--;
slideBullets[current].classList.add("clicked");
});
rightSide.addEventListener("click", function () {
reset();
if (current === slideImages.length - 1) {
current = - 1;
}
slideImages[current + 1].style.display = 'block';
current++;
slideBullets[current].classList.add("clicked");
});
};
function showBulletsImages() {
for (let i = 0; i < slideBullets.length; i++) {
slideBullets[i].addEventListener("click", function () {
reset();
slideImages[i].style.display = 'block';
slideBullets[i].classList.add("clicked");
current = i;
});
}
};
function autoSlide() {
setInterval(function () {
rightSide.click();
slideBullets[current].classList.add('clicked')
}, 2000);
};
return {
reset: reset(),
showImages: showImages(),
arrowSlide: arrowSlide(),
showBulletsImages: showBulletsImages(),
autoSlide: autoSlide()
};
})();
var toggleMenu = (function () {
var mainTopics = document.getElementById("maintopics");
mainTopics.addEventListener("click", function (e) {
e.preventDefault();
e.stopImmediatePropagation();
mainTopics.classList.toggle("show");
});
document.addEventListener("click", function (e) {
if (e.target.id !== 'arrow-right') {
mainTopics.classList.remove("show");
}
});
return {
toggleMenu: toggleMenu()
};
})();
body {
margin: 0;
}
li, a{
text-decoration: none;
list-style-type: none;
text-decoration-line: none;
color: black;
}
/*main-menu*/
#mainmenu {
position: relative;
}
#mainmenu ul {
margin: 0;
padding: 0;
}
#mainmenu li {
display: inline-block;
}
#mainmenu a {
display: block;
width: 100px;
padding: 10px;
border: 1px solid;
text-align: center;
}
/*sub-topics*/
#subtopics {
position: absolute;
display: none;
margin-top: 10px;
width: 100%;
left: 0;
}
#maintopics.show #subtopics {
display: block;
}
#subtopics ul {
margin: 0;
padding: 0;
}
#subtopics li {
display: block;
}
#subTopics a {
text-align: left;
}
/*columns*/
#column1, #column2, #column3 {
position: relative;
float: left;
left: 125px;
margin: 0px 5px 0px 0px;
}
/*hover underline*/
#mainmenu li:hover {
text-decoration: underline;
}
/*slideshow*/
#slideshow {
position: relative;
width: 100%;
height: 100%;
}
#slide1 {
background-image: url(https://preview.ibb.co/mV3TR7/1.jpg);
}
#slide2 {
background-image: url(https://preview.ibb.co/bSCBeS/2.jpg);
}
#slide3 {
background-image: url(https://preview.ibb.co/kgG9Yn/3.jpg);
}
.slide {
background-repeat: no-repeat;
background-position: center;
background-size: 800px 400px;
width: 800px;
height: 400px;
margin: auto;
margin-top: 40px;
}
.slide-contain {
position: absolute;
left: 50%;
bottom: 50%;
transform: translate3d(-50%,-50%,0);
text-align: center;
}
.slide-contain span {
color: white;
}
/*arrow*/
.arrow {
position: absolute;
cursor: pointer;
top: 200px;
width: 0;
height: 0;
border-style: solid;
}
.arrow:hover {
background-color: #e0dede;
transition: background-color 0.6s ease;
}
#arrow-left {
position: absolute;
border-width: 30px 40px 30px 0px;
border-color: transparent gray transparent transparent;
left: 0;
margin-left: 300px;
}
#arrow-right {
border-width: 30px 0px 30px 40px;
border-color: transparent transparent transparent gray;
right: 0;
margin-right: 300px;
}
/*bullets*/
#slidebullet {
position: relative;
top: -30px;
text-align: center;
}
.bullets {
display: inline-block;
background-color: gray;
width: 15px;
height: 15px;
border-radius: 10px;
cursor: pointer;
transition: background-color 0.6s ease;
}
.clicked {
background-color: #ff0000;
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" type="text/css" href="index.css" />
</head>
<body>
<header></header>
<nav>
<div id="mainmenu">
<ul>
<li>Logo</li>
<li>Home</li>
<li id="maintopics">Topics
<div id="subtopics">
<div id="column1" class="columns">
<ul>
<li>example1</li>
<li>example2</li>
</ul>
</div>
</div>
</li>
</ul>
</div>
</nav>
<div id="slideshow">
<div id="slide1" class="slide">
<div class="slide-contain">
<span>Image One</span>
</div>
</div>
<div id="slide2" class="slide">
<div class="slide-contain">
<span>Image Two</span>
</div>
</div>
<div id="slide3" class="slide">
<div class="slide-contain">
<span>Image Three</span>
</div>
</div>
<div id="slidebullet">
<div id="bullet1" class="bullets"></div>
<div id="bullet2" class="bullets"></div>
<div id="bullet3" class="bullets"></div>
</div>
<div id="arrow-left" class="arrow"></div>
<div id="arrow-right" class="arrow"></div>
</div>
<script src="jquery.js"></script>
<script src="index.js"></script>
<script>
</script>
</body>
</html>
Then i changed position of functions
var toggleMenu = (function () {
var mainTopics = document.getElementById("maintopics");
mainTopics.addEventListener("click", function (e) {
e.preventDefault();
e.stopImmediatePropagation();
mainTopics.classList.toggle("show");
});
document.addEventListener("click", function (e) {
if (e.target.id !== 'arrow-right') {
mainTopics.classList.remove("show");
}
});
return {
toggleMenu: toggleMenu()
};
})();
var slideShow = (function () {
var slideImages = document.getElementsByClassName("slide");
var leftSide = document.getElementById("arrow-left");
var rightSide = document.getElementById("arrow-right");
var slideBullets = document.getElementsByClassName("bullets");
var current = 0;
function reset() {
for (let i = 0; i < slideImages.length; i++) {
slideImages[i].style.display = 'none';
slideBullets[i].classList.remove("clicked");
}
};
function showImages() {
for (let i = 0; i < slideImages.length; i++) {
slideImages[0].style.display = 'block';
slideBullets[current].classList.add("clicked");
}
};
function arrowSlide() {
leftSide.addEventListener("click", function () {
reset();
if (current === 0) {
current = slideImages.length;
}
slideImages[current - 1].style.display = 'block';
current--;
slideBullets[current].classList.add("clicked");
});
rightSide.addEventListener("click", function () {
reset();
if (current === slideImages.length - 1) {
current = - 1;
}
slideImages[current + 1].style.display = 'block';
current++;
slideBullets[current].classList.add("clicked");
});
};
function showBulletsImages() {
for (let i = 0; i < slideBullets.length; i++) {
slideBullets[i].addEventListener("click", function () {
reset();
slideImages[i].style.display = 'block';
slideBullets[i].classList.add("clicked");
current = i;
});
}
};
function autoSlide() {
setInterval(function () {
rightSide.click();
slideBullets[current].classList.add('clicked')
}, 2000);
};
return {
reset: reset(),
showImages: showImages(),
arrowSlide: arrowSlide(),
showBulletsImages: showBulletsImages(),
autoSlide: autoSlide()
};
})();
The issue seems to be with this
return {
toggleMenu: toggleMenu()
};
inside the toggleMenu immediately invoking function . This IIFE does not have any toggleMenu function
Beside return like
return {
reset: reset(),
showImages: showImages(),
arrowSlide: arrowSlide(),
showBulletsImages: showBulletsImages(),
autoSlide: autoSlide()
};
is not appropriate ,replace it with the following
There is no reason tha slideShow has to IIFE
return {
reset: reset,
showImages: showImages,
arrowSlide: arrowSlide,
showBulletsImages: showBulletsImages,
autoSlide: autoSlide
};
Here is a working demo at stackblitz

Add active class on pagination when corresponding slide is showing

I have a simple image slider, with pagination controls.
I have coded it to add and remove an "active" class on the pagination
buttons on click. I would also like them to have the active class when the corresponding slide is showing.
How can I modify my code to achieve this?
<div id="slideshow">
<ul id="slides">
<li class="slide showing">
<div class="slide-description">
<h1 class="slide-title">All-in-one EV charging solution.</h1>
<p> Easy to use. Connected with smart charging capabilities. Our charging stations can be used at home,
work or in public.</p>
</div>
</li>
<li class="slide">
<div class="slide-description">
<h1 class="slide-title">Charging at work- a case study.</h1>
<p>In this new series of charging case studies, we dive into into the reasons why EV-Box partners are taking the green route.</p>
</div>
</li>
<li class="slide"> <div class="slide-description">
<h1 class="slide-title">Finding the best solution for your charging routine.</h1>
<p>
This whitepaper highlights the key answers that will guide you to acharging solution that best serves your needs.
</p>
</div>
</li>
</ul>
<button class="controls" id="previous"></button>
<button class="controls" id="next"></button>
<div id="pagination"></div>
var slides = document.querySelectorAll('#slides .slide'); // get all the slides
var currentSlide = 0;
var slideInterval = setInterval(nextSlide, 6000);
function nextSlide() {
goToSlide(currentSlide + 1);
}
function previousSlide() {
goToSlide(currentSlide - 1);
}
function goToSlide(n) {
slides[currentSlide].className = 'slide';
currentSlide = (n + slides.length) % slides.length;
slides[currentSlide].className = 'slide showing';
}
//Previous and Next controls
var next = document.getElementById('next');
var previous = document.getElementById('previous');
next.onclick = function() {
nextSlide();
};
previous.onclick = function() {
previousSlide();
};
//Pagination controls
var p = document.getElementById('pagination');
var phtml = '';
for(var i = 0; i < slides.length; i++) {
phtml += '<button></button>'; // create the pagination buttons for each slide
}
p.innerHTML = phtml; //insert the html for the buttons
var pbuttons = p.querySelectorAll('button'); // grab all the buttons
var activeButton = null; // reference to active button
for(var i = 0; i < pbuttons.length; i++) {
pbuttons[i].onclick = (function(n) {
return function() {
if(activeButton)
activeButton.classList.remove('active'); // delete class from old active button
activeButton = this;// change ref, this is current button
activeButton.classList.add('active');// add class for new
goToSlide(n);
};
})(i);
}
#slider {
min-height: 400px;
position: relative;
#slides {
min-height: 400px;
padding: 0;
margin: 0;
list-style-type: none;
.slide {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
opacity: 0;
z-index: 1;
min-height: 400px;
box-sizing: border-box;
background: $black;
color: $white;
display: flex;
align-items: center;
-webkit-justify-content: flex-end;
justify-content: flex-end;
-webkit-transition: opacity 1s;
-moz-transition: opacity 1s;
transition: opacity 1s;
&.showing {
opacity: 1;
z-index: 2;
}
&:nth-of-type(1) {
#include backImage('../images/evbox1.jpg');
}
&:nth-of-type(2){
#include backImage('../images/evbox2.jpg');
}
&:nth-of-type(3) {
#include backImage('../images/evbox3.jpg');
}
}
.slide-description {
width: 500px;
.slide-title {
width: 90%;
font-family: 'Open Sans', sans-serif;
font-size: 44px;
text-shadow: 0 2px 3px rgba($black, .2);
line-height: 1.1em;
margin-bottom: 10px;
}
p {
margin-bottom: 15px;
width: 90%;
font-size: 20px;
font-family: 'Open Sans', sans-serif;
font-weight: 300;
text-shadow: 0 2px 3px rgba($black, .2);
}
.btn {
#include button($blue, $font-color, $shadow-color);
}
}
#include respond-to($mobile) {
#media only screen and (max-width: $mobile) {
.slide:nth-of-type(3) {
background-position: left 0;
}
.slide-description {
height: 100%;
width: 100%;
padding: 8em 5em;
position: static;
text-align: center;
.slide-title {
font-size: 30px;
width: 100%;
}
.btn {
padding: 8px 16px;
}
}
p {
display: none;
}
}
}
}
}
/*Previous and Next Controls*/
.controls {
position: absolute;
top: 42%;
z-index: 10;
background: url('http://www.ev-box.com/Evbox-EN/includes/themes/evbox/assets/images/sprites#2x.png') no-repeat;
height: 50px;
width: 30px;
background-size: 369px 240px;
outline: 0;
border: 0;
cursor: pointer;
}
#previous {
right: 10px;
background-position: -50px -121px;
}
#next {
left: 10px;
background-position: -16px -121px;
}
// Pagination
#pagination {
position: absolute;
bottom: 30px;
right: 50%;
z-index: 10;
button {
border-radius: 50%;
border: 1px solid $white;
background-color: $white;
opacity: .8;
width: 14px;
height: 14px;
min-height: 14px;
border-width: 0;
margin-right: 5px;
&.active {
width: 15px;
height: 15px;
min-height: 15px;
border: 1px solid $white;
background-color: $primary;
opacity: 1;
&:focus {
outline: 0;
}
}
}
}
I updated the javascript as shown below. Use this in your code pen. you can see the diffrence. If you click next and previous button the corresponding pagination will be highlighted by using this javascript
document.addEventListener("DOMContentLoaded", function() {
var slides = document.querySelectorAll('#slides .slide'); // get all the slides
const totalSlides = 2 // Total number of slides count
var currentSlide = 0; // current slide
var previousSlide = totalSlides;
// var slideInterval = setInterval(nextSlide, 1000);
function nextSlide() {
previousSlide = currentSlide
if(totalSlides > currentSlide){
currentSlide += 1
}
else currentSlide = 0
goToSlide();
}
function PreviousSlide() {
if(currentSlide == 0){
previousSlide = currentSlide
currentSlide = totalSlides
}
else{
previousSlide = currentSlide
currentSlide -=1
}
goToSlide();
}
function goToSlide() {
slides[previousSlide].className = 'slide';
slides[currentSlide].className = 'slide showing';
var currentSlideButton = "button"+currentSlide
var previousSlideButton = "button"+previousSlide
document.getElementById(currentSlideButton).classList.add('active');
document.getElementById(previousSlideButton).classList.remove('active');
}
//Previous and Next controls
var next = document.getElementById('next');
var previous = document.getElementById('previous');
next.onclick = function() {
PreviousSlide();
};
previous.onclick = function() {
nextSlide();
};
//Pagination controls
var p = document.getElementById('pagination');
var phtml = '';
for(var i = 0; i < slides.length; i++) {
phtml += '<button id=button'+i+'></button>'; // create the pagination buttons for each slide
}
p.innerHTML = phtml; //insert the html for the buttons
var pbuttons = p.querySelectorAll('button'); // grab all the buttons
var activeButton = null; // reference to active button
for(var i = 0; i < pbuttons.length; i++) {
pbuttons[i].onclick = (function(n) {
return function() {
if(activeButton)
activeButton.classList.remove('active'); // delete class from old active button
activeButton = this;// change ref, this is current button
activeButton.classList.add('active');// add class for new
goToSlide(n);
};
})(i);
}
goToSlide();// Initialising goToSlide method
});

Categories