change background colour of div on carousel - javascript

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>

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!

Keyframes animation for a nav bar won't retrigger at a different position

I've been trying to develop a CSS keyframes animation for a navigation bar.
You can see in the code snippet how the animation works - the red line is animated when the user clicks an element of the nav bar. The first element of the nav bar is active by default (the red line is under this element). When an element is clicked, the JS takes the properties of the animation element, as well as the properties of the element that was clicked. These properties are incorporated into new keyframes that are inserted into the single keyframes rule.
When the second element is clicked, the animation runs successfully from element 1 --> 2. The animation also runs successfully from element 1 --> 3.
But after the animation plays from element 1 --> 2, it won't play from element 2 --> 3. The animationend event does not trigger (I checked this). As of now, I'm only concerned with the animation going forwards.
After researching, I tried several methods to fix this. Removing and reattaching the animation class does not work, even with a DOM reflow being triggered. Changing the animation-play-state from 'running' to 'paused' does not work either. Other solutions, such as changing the animation-name to 'none' and then back, only generate more problems, like the position of the animation element being reset upon the ending of the animation. I truly do not know how to fix this.
I would prefer to make a flexible keyframes animation, such as this, rather than brute-forcing it. A brute force scenario would include making 6 different keyframes rules, and I want the code to be applicable to any number of elements in the navigation bar. Adding keyframes rules for every addition of an element would require exponentially more code each addition.
Thanks.
~ Code for demo ~
var keyframes = findKeyframesRule('movey');
$(document).ready(() => {
$('div.one').click(() => {
if (!($('div.one').hasClass('active'))) {
/* unfinished */
}
})
$('div.two').click(() => {
if (!($('div.two').hasClass('active'))) {
/* transfer active class */
$('div.active').removeClass('active');
$('div.two').addClass('active');
var left = ( parseInt($('div.absolute').css('left')) / $(window).width() ) * 100;
/* reset keyframes before animation */
clearKeyframes();
/* add new keyframes for when div.two is clicked */
keyframes.appendRule("0% { width: 15%; left: " + left + "%;}");
keyframes.appendRule("49.99% { width: 30%; left: " + left + "%; right: 70%;}");
keyframes.appendRule("50% { width: 30%; left: unset; right: 70%;}");
keyframes.appendRule("100% { width: 15%; right: 70%;}");
/* first animation - add animation class */
if (!($('div.absolute').hasClass('animateMovey'))) {
$('div.absolute').addClass('animateMovey');
/* animations after first - remove and reattach animation class with new keyframes */
} else {
$('div.absolute').removeClass('animateMovey');
$('div.absolute').addClass('animateMovey');
}
/* ensure animation occurs */
$('div.animateMovey').on('animationend', () => {
console.log('Animation ended');
})
}
})
$('div.three').click(() => {
if (!($('div.three').hasClass('active'))) {
$('div.active').removeClass('active');
$('div.three').addClass('active');
var left = ( parseInt($('div.absolute').css('left')) / $(window).width() ) * 100;
var width = 45 - left;
clearKeyframes();
keyframes.appendRule("0% { width: 15%; left: " + left + "%;}");
keyframes.appendRule("49.99% { width: " + width + "%; left: " + left + "%; right: 55%;}");
keyframes.appendRule("50% { width: " + width + "%; left: unset; right: 55%;}");
keyframes.appendRule("100% { width: 15%; right: 55%;")
if (!($('div.absolute').hasClass('animateMovey'))) {
$('div.absolute').addClass('animateMovey');
} else {
$('div.absolute').removeClass('animateMovey');
$('div.absolute').addClass('animateMovey');
}
$('div.animateMovey').on('animationend', () => {
console.log('Animation ended');
})
}
})
})
function findKeyframesRule(rule) {
var ss = document.styleSheets;
for (var i = 0; i < ss.length; ++i) {
for (var j = 0; j < ss[i].cssRules.length; ++j) {
if (ss[i].cssRules[j].type == window.CSSRule.KEYFRAMES_RULE && ss[i].cssRules[j].name == rule)
return ss[i].cssRules[j];
}
}
return null;
}
function clearKeyframes() {
for (var i = 0; i <= 3; ++i) {
if (keyframes[0]) {
var keyToRemove = keyframes[0].keyText;
keyframes.deleteRule(keyToRemove);
}
}
}
body {
margin: 0;
}
div.nav {
position: relative;
display: block;
overflow: hidden;
width: 100%;
}
div.nav div {
float: left;
width: 15%;
height: 75px;
}
div.nav div:hover {
opacity: 0.5;
}
div.one {
background-color: #7a7a7a;
}
div.two {
background-color: #9e9e9e;
}
div.three {
background-color: #bdbdbd;
}
.active {
box-shadow: inset 3px 5px 6px #000;
}
div.animateMovey {
animation-name: movey;
animation-duration: 0.6s;
animation-fill-mode: forwards;
animation-timing-function: ease-in-out;
}
div.relative {
position: relative;
width: 100%;
height: 20px;
}
div.absolute {
position: absolute;
background-color: #ff8c69;
width: 15%;
height: 100%;
}
#keyframes movey {
100% { }
}
<div>
<div class="nav">
<div class="one active"></div>
<div class="two"></div>
<div class="three"></div>
</div>
<div class="relative">
<div class="absolute"></div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Interesting question. I'm not sure why the event is not re-triggering in this case, but will suggest a few changes to your approach:
Aim to animate transform and opacity instead of width and left, right
(https://developers.google.com/web/fundamentals/design-and-ux/animations/animations-and-performance)
One way to do this is to use a separate red element under each box, and slide it left or right using transform
Use animation-delay to create the lengthening and shortening effect
Try to reuse the animation logic, so it will work regardless of the number of items.
The challenging part of this effect is managing the opacity of each line. I've used animationEnd to help with that, and it appears to work fine.
Additional comments in the example code. It could be improved by handling clicks while animation is active, consolidating animation functions etc. You could also vary the animation duration depending on the number of items.
let boxes = null;
let lines = null;
let fromIndex = 0;
let toIndex = 0;
const ANIMATION_DURATION = 0.1; // seconds
const animation = {
animating: false,
lines: [],
direction: "right",
inOrOut: "in"
};
function getEls() {
boxes = [...document.querySelectorAll(".box")];
lines = [...document.querySelectorAll(".line")];
}
function setAnimationDuration() {
lines.forEach((line) => {
line.style.animationDuration = `${ANIMATION_DURATION}s`;
});
}
function addEvents() {
boxes.forEach((box, index) => {
box.addEventListener("click", () => {
// User has clicked the currently active box
if (fromIndex === index) return;
// Line is currently animating
if (animation.animating) return;
toIndex = index;
updateActiveBox();
handleLineAnimation();
});
});
document.addEventListener("animationend", (e) => {
// Maintain opacity on lines that animate in
if (animation.inOrOut === "in") {
e.target.style.opacity = 1;
}
});
}
function updateActiveBox() {
boxes[fromIndex].classList.remove("active");
boxes[toIndex].classList.add("active");
}
function updateActiveLine(line) {
lines[fromIndex].classList.remove("active");
line.classList.add("active");
}
function handleLineAnimation() {
animation.animating = true;
animation.lines = [];
if (toIndex > fromIndex) {
animation.direction = "right";
for (let i = fromIndex; i <= toIndex; i++) {
animation.lines.push(lines[i]);
}
} else {
animation.direction = "left";
for (let i = fromIndex; i >= toIndex; i--) {
animation.lines.push(lines[i]);
}
}
animate();
}
function animate() {
const wait = (animation.lines.length - 1) * ANIMATION_DURATION * 1000;
animation.inOrOut = "in";
animateIn();
setTimeout(() => {
resetLine();
updateActiveLine(lines[toIndex]);
animation.inOrOut = "out";
animateOut();
setTimeout(() => {
resetLine();
onAnimationComplete();
}, wait);
}, wait);
}
function animateIn() {
const {
direction,
lines
} = animation;
lines.forEach((line, index) => {
// index = 0 is currently active, no need to animate in
if (index > 0) {
line.classList.add(`animate-in-${direction}`);
line.style.animationDelay = `${(index - 1) * ANIMATION_DURATION}s`;
}
});
}
function animateOut() {
const {
direction,
lines
} = animation;
lines.forEach((line, index) => {
// lines.length - 1 is new active, don't animate out
if (index < lines.length - 1) {
line.classList.remove(`animate-in-${direction}`);
line.classList.add(`animate-out-${direction}`);
line.style.animationDelay = `${index * ANIMATION_DURATION}s`;
}
});
}
function resetLine() {
const {
direction,
lines,
inOrOut
} = animation;
lines.forEach((line) => {
line.classList.remove(`animate-${inOrOut}-${direction}`);
line.style.animationDelay = null;
// After animating out, remove inline opacity
if (inOrOut === "out") {
if (!line.classList.contains("active")) {
line.style.opacity = "";
}
}
});
}
function onAnimationComplete() {
animation.animating = false;
fromIndex = toIndex;
}
function init() {
getEls();
setAnimationDuration();
addEvents();
}
function reset() {
fromIndex = 0;
init();
lines.forEach((line, index) => {
line.classList.remove('active');
line.style.opacity = "";
boxes[index].classList.remove('active');
});
boxes[0].classList.add("active");
lines[0].classList.add("active");
}
init();
// DEBUG
document.getElementById("debug").addEventListener("change", (e) => {
document.querySelector("nav").classList.toggle("debug-on");
});
document.getElementById("add").addEventListener("click", (e) => {
const div = document.createElement("div");
div.classList.add("box");
div.innerHTML = '<div class="new"></div><span class="line"></span>';
document.querySelector("nav").appendChild(div);
reset();
});
document.getElementById("remove").addEventListener("click", (e) => {
const indexToRemove = boxes.length - 1;
if (indexToRemove > 0) {
const box = boxes[indexToRemove];
box.parentNode.removeChild(box);
reset();
}
});
nav {
display: flex;
flex-wrap: wrap;
overflow: hidden;
}
.debug-on .line {
border: 1px solid;
box-sizing: border-box;
opacity: 0.2;
}
.box {
display: flex;
flex-direction: column;
position: relative;
float: left;
flex: 0 0 15%;
/* Allows the line to slide left or right with opacity: 1 */
overflow: hidden;
}
.box>div {
cursor: pointer;
height: 75px;
}
.one {
background-color: #7a7a7a;
}
.two {
background-color: #9e9e9e;
}
.three {
background-color: #bdbdbd;
}
.new {
background-color: pink;
border: 1px solid;
box-sizing: border-box;
}
.line {
background-color: #ff8c69;
height: 20px;
opacity: 0;
pointer-events: none;
width: 100%;
animation-fill-mode: forwards;
animation-timing-function: linear;
}
.active>div {
box-shadow: inset 3px 5px 6px #000;
}
.box:hover div {
opacity: 0.5;
}
.line.active {
opacity: 1;
}
.line.show {
opacity: 1;
}
.animate-in-right {
animation-name: SLIDE_IN_RIGHT;
}
.animate-out-right {
animation-name: SLIDE_OUT_RIGHT;
}
.animate-in-left {
animation-name: SLIDE_IN_LEFT;
}
.animate-out-left {
animation-name: SLIDE_OUT_LEFT;
}
#keyframes SLIDE_IN_RIGHT {
from {
opacity: 1;
transform: translateX(-100%);
}
to {
opacity: 1;
transform: translateX(0);
}
}
#keyframes SLIDE_OUT_RIGHT {
from {
opacity: 1;
transform: translateX(0);
}
to {
opacity: 1;
transform: translateX(100%);
}
}
#keyframes SLIDE_IN_LEFT {
from {
opacity: 1;
transform: translateX(100%);
}
to {
opacity: 1;
transform: translateX(0);
}
}
#keyframes SLIDE_OUT_LEFT {
from {
opacity: 1;
transform: translateX(0);
}
to {
opacity: 1;
transform: translateX(-100%);
}
}
/* for demo only */
.debug {
background: #eee;
padding: 1rem;
display: inline-flex;
flex-direction: column;
font: 14px/1 sans-serif;
position: fixed;
bottom: 0;
right: 0;
}
.debug button {
margin-top: 1rem;
padding: .25rem;
}
<nav>
<div class="box active">
<div class="one"></div>
<span class="line active"></span>
</div>
<div class="box">
<div class="two"></div>
<span class="line"></span>
</div>
<div class="box">
<div class="three"></div>
<span class="line"></span>
</div>
</nav>
<br><br>
<div class="debug">
<label for="debug">Debug Lines <input type="checkbox" id="debug">
</label>
<button id="add">Add cell</button>
<button id="remove">Delete cell</button>
</div>

How can I hide all slides and display the current one in JavaScript?

I'm creating a slider in Vanilla JavaScript.
I have a basic foundation.
Right now I'm not sure how to hide all of the other slides, and display only the current one. Then on the next/prev, show show the next slide, and hide the one that was before.
I have tried few things, but neither did work.
Here is the codepen: https://codepen.io/Aurelian/pen/LBGWpd?editors=0010
// Problem: Make the slides slide one after another
// and make the buttons work prev and next to bring prev or next slide
// Solution
// Select all slides
// On next/prev, get the left/right animate from 0 to 100 or from 0 to -100%
// On button press, get the prev/next parent node
// Add active class on the shown
// Solution Part 2
// Select all slides
// Get the length of the slides
// Display none on every slideItem
// Get the current slide
// Display block/flex on current slide
// On next, advance the slider index by 1
// On prev, advance the slider index by -1
// Make the slider slide every 3sec with setInterval
// Even listener on slider mousehover, stop the autoslide and add "PAUSED" HTML - add
// On live the slder, unpause and remove the HTML "PAUSED"
document.addEventListener('DOMContentLoaded', function() {
var slider = document.querySelector(".slider"),
sliderList = document.querySelector(".slider__list"),
sliderItems = document.querySelectorAll(".slider__item"),
sliderBtnPrev = document.querySelector(".slider__buttons--prev"),
sliderBtnNext = document.querySelector(".slider__buttons--next"),
sliderItemsLength = sliderItems.length,
currentIndex = 0,
isPaused = false;
function prevSlide() {
sliderItems[currentIndex].classList.remove('is-active');
currentIndex = (currentIndex + sliderItemsLength - 1) % sliderItemsLength;
sliderItems[currentIndex].classList.add('is-active');
}
function nextSlide() {
sliderItems[currentIndex].classList.remove('is-active');
currentIndex = (currentIndex + 1) % sliderItemsLength;
sliderItems[currentIndex].classList.add('is-active');
}
function advance() {
isPaused = false;
if ((isPaused = false) = 1) {
setInterval(function() {
nextSlide();
}, 3000);
}
}
sliderBtnPrev.addEventListener('click', function() {
prevSlide();
});
sliderBtnNext.addEventListener('click', function() {
nextSlide();
});
slider.addEventListener('mouseover', function() {
isPaused = true;
});
slider.addEventListener('mouseout', function() {
isPaused = false;
});
advance();
// On press next, change slide
// sliderItems.forEach(function(sliderItem) {
// sliderItem.style.display = "none";
// });
// function prevSlide() {
// console.log('prev slide');
// }
// function nextSlide() {
// console.log('next slide');
// // if (currentIndex) {
// // console.log(sliderItems[currentIndex])
// // }
// // sliderItemsLength.push[1];
// // currentIndex + 1;
// // console.log(currentIndex < (sliderItemsLength + 1));
// // console.log(sliderItems[currentIndex + 1])
// // if (sliderItemsLength < -1) {
// // sliderItemsLength++;
// // }
// // if (currentIndex < (sliderItemsLength + 1)) {
// // sliderItems[currentIndex].classList.add('is-active');
// // }
// // if (numbers.length > 3) {
// // numbers.length = 3;
// // }
// // myArray[myArray.length - 1] + 1
// if (currentIndex < (sliderItemsLength + 1)) {
// sliderItems[currentIndex].classList.add('is-active');
// currentIndex++;
// } else {
// sliderItems.style.display = "none";
// }
// }
});
* {
box-sizing: border-box;
}
ul,
ol {
margin: 0;
padding: 0;
list-style: none;
}
.slider {
position: relative;
height: 350px;
width: 100%;
}
.slider__list {
height: 100%;
overflow: hidden;
position: relative;
}
.slider__item {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
width: 100%;
display: none;
height: 100%;
width: 100%;
position: absolute;
}
.slider__item.is-active {
display: flex;
}
.slider__item:first-child {
background-color: orange;
}
.slider__item:nth-child(2) {
background-color: gold;
}
.slider__item:last-child {
background-color: green;
}
.slider__title {
color: white;
font-weight: bold;
font-size: 1.5em;
}
.slider__buttons {
position: absolute;
right: 0;
left: 0;
top: 50%;
}
.slider__buttons--prev {
height: 40px;
width: 40px;
background-color: red;
cursor: pointer;
position: absolute;
bottom: 0;
margin: auto;
top: 0;
left: 30px;
}
.slider__buttons--next {
height: 40px;
width: 40px;
background-color: red;
cursor: pointer;
position: absolute;
bottom: 0;
top: 0;
margin: auto;
right: 30px;
}
<div class="container">
<div class="slider">
<ul class="slider__list">
<li class="slider__item is-active">
<span class="slider__title">1</span>
</li>
<li class="slider__item">
<span class="slider__title">2</span>
</li>
<li class="slider__item">
<span class="slider__title">3</span>
</li>
</ul>
<div class="slider__buttons">
<span class="slider__buttons--prev"></span>
<span class="slider__buttons--next"></span>
</div>
<!-- <ul class="slider__nav">
<li class="slider__nav-item"></li>
<li class="slider__nav-item"></li>
<li class="slider__nav-item"></li>
</ul> -->
</div>
</div>
You need to hide all slides by default display: none then define a class is-active to change the display to flex
Start counting from -1
The formula to calculate the next slide is :
(currentIndex + 1) % sliderItemsLength
The formula to calculate the prev slide is :
(currentIndex + sliderItemsLength - 1) % sliderItemsLength
document.addEventListener('DOMContentLoaded', function() {
var sliderList = document.querySelector(".slider__list"),
sliderItems = document.querySelectorAll(".slider__item"),
sliderBtnPrev = document.querySelector(".slider__buttons--prev"),
sliderBtnNext = document.querySelector(".slider__buttons--next"),
sliderItemsLength = sliderItems.length,
currentIndex = -1;
function prevSlide() {
sliderItems[currentIndex].classList.remove('is-active');
currentIndex = (currentIndex + sliderItemsLength - 1) % sliderItemsLength;
sliderItems[currentIndex].classList.add('is-active');
}
function nextSlide() {
if (currentIndex > 0) sliderItems[currentIndex].classList.remove('is-active');
else sliderItems[0].classList.remove('is-active');
currentIndex = (currentIndex + 1) % sliderItemsLength;
sliderItems[currentIndex].classList.add('is-active');
}
sliderBtnPrev.addEventListener('click', function() {
prevSlide();
});
sliderBtnNext.addEventListener('click', function() {
nextSlide();
});
nextSlide();
});
* {
box-sizing: border-box;
}
ul,
ol {
margin: 0;
padding: 0;
list-style: none;
}
.slider {
position: relative;
height: 350px;
width: 100%;
}
.slider__list {
height: 100%;
overflow: hidden;
position: relative;
}
.slider__item {
display: none;
align-items: center;
justify-content: center;
height: 100%;
width: 100%;
height: 100%;
width: 100%;
position: absolute;
}
.slider__item.is-active {
display: flex;
}
.slider__item:first-child {
background-color: orange;
}
.slider__item:nth-child(2) {
background-color: red;
}
.slider__item:last-child {
background-color: green;
}
.slider__title {
color: white;
font-weight: bold;
font-size: 1.5em;
}
.slider__buttons {
position: absolute;
right: 0;
left: 0;
top: 50%;
}
.slider__buttons--prev {
height: 40px;
width: 40px;
background-color: red;
cursor: pointer;
position: absolute;
bottom: 0;
margin: auto;
top: 0;
left: 30px;
}
.slider__buttons--next {
height: 40px;
width: 40px;
background-color: red;
cursor: pointer;
position: absolute;
bottom: 0;
top: 0;
margin: auto;
right: 30px;
}
<div class="container">
<div class="slider">
<ul class="slider__list">
<li class="slider__item">
<span class="slider__title">1</span>
</li>
<li class="slider__item">
<span class="slider__title">2</span>
</li>
<li class="slider__item">
<span class="slider__title">3</span>
</li>
</ul>
<div class="slider__buttons">
<span class="slider__buttons--prev"></span>
<span class="slider__buttons--next"></span>
</div>
<!-- <ul class="slider__nav">
<li class="slider__nav-item"></li>
<li class="slider__nav-item"></li>
<li class="slider__nav-item"></li>
</ul> -->
</div>
</div>

Converting to the ajax async false alternative because of depreciation

I've done a research on this question and found some solutions. However, not every one of them worked. As I understand, async false makes a UI block, which shouldn't be. I could use an overlay until ajax request is completed and on the request success, hide the overlay.
That was my try using a callback argument in the getNewQuote() function (only a small snippet of it):
var getNewQuote = function(callback) {
var quote = {};
setTimeout(function() {
quote.text = 'Example';
quote.author = 'Example';
callback();
return quote;
}, 4000);
};
getNewQuote(function() {
console.log("DONE");
var getRandomColor = function() {
var colors = [
"#ff9966",
"#7f00ff",
"#396afc",
"#0cebeb",
"#06beb6",
"#642b73",
"#36d1dc",
"#cb356b",
"#3a1c71",
"#ef3b36",
"#159957",
"#000046",
"#007991",
"#56ccf2",
"#f2994a",
"#e44d26",
"#4ac29a",
"#f7971e",
"#34e89e",
"#6190e8",
"#3494e6",
"#ee0979"
],
randomNumber = Math.floor(Math.random() * colors.length);
return colors[randomNumber];
};
var updateText = function($t, qt) {
var twitter = "https://twitter.com/intent/tweet?hashtags=quotes&related=freecodecamp&text=";
twitter += '"' + qt.text + '" ';
twitter += qt.author;
var tumblr = "https://www.tumblr.com/widgets/share/tool?posttype=quote&tags=quotes,freecodecamp&caption=";
tumblr += qt.author;
tumblr += "&content=";
tumblr += qt.text;
tumblr += "&canonicalUrl=https%3A%2F%2Fwww.tumblr.com%2Fbuttons&shareSource=tumblr_share_button";
var $icon = $("<i class='fa fa-quote-left'>")
.prop("aria-hidden", true);
$t.find(".quote-text").html("").append($icon, qt.text);
$t.find(".quote-author").html("- " + qt.author);
$("#tweet-quote").attr("href", twitter);
$("#tumblr-quote").attr("href", tumblr);
};
var calcNewHeight = function(q) {
var $temp = $("<div>", {
class: "quote-container temp",
}).appendTo($("body"));
$temp.append($("<div>", {
class: "quote-text"
}), $("<div>", {
class: "quote-author"
}));
updateText($temp, q);
var h = $temp.height() + 40;
$temp.remove();
return h;
};
var changeColor = function(newColor) {
$("body, .button:not(#new-quote)").animate({
backgroundColor: newColor
});
$("#new-quote").animate({
color: newColor
});
$(".quote-text, .quote-author").css("color", newColor);
if ($("#modStyle").length === 0) {
$("head").append(
"<style id='modStyle'>#new-quote:before {background:" + newColor + ";}</style>"
);
} else {
$("head style#modStyle").html("#new-quote:before {background:" + newColor + ";}");
}
};
var getQuote = function() {
var nq, nc, nh = 0;
nq = getNewQuote();
nc = getRandomColor();
nh = calcNewHeight(nq);
$(".quote-container").children().css("opacity", 0);
changeColor(nc);
$(".quote-container, #new-quote").animate({
height: nh,
}, {
duration: 1000,
queue: false
});
$(".quote-container").animate({
padding: "2.5em"
}, {
duration: 1000,
queue: false
});
$("#new-quote").animate({
padding: "2.5em .75em"
}, {
duration: 1000,
queue: false
});
updateText($(".quote-container"), nq);
$(".quote-container").children().fadeTo(750, 1);
};
$("#new-quote").on("click", getQuote);
$(".quote-container, #new-quote").css({
visibility: "visible",
height: 0
});
$("#new-quote").css("padding", "0 .75em");
getQuote();
});
html,
body {
height: 100%;
width: 100%;
}
body {
margin: 0;
padding: 0;
background: #333;
color: #333;
font-family: sans-serif;
}
.v-wrap {
height: 100%;
text-align: center;
}
.v-wrap:before {
content: "";
display: inline-block;
vertical-align: middle;
width: 0;
height: 100%;
}
.quote-container {
width: 31.25rem;
background: #fff;
margin: 0;
display: inline-block;
vertical-align: middle;
border-radius: 0.1875rem;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
visibility: hidden;
padding: 0 2.5rem;
}
.quote-text {
font-size: 1.625rem;
}
.quote-text i {
margin-right: 0.6rem;
}
.quote-text p {
display: inline;
}
.quote-author {
font-size: 1rem;
margin: 0 0.4rem 2rem 0;
text-align: right;
}
.button {
padding: 0.75rem;
text-align: center;
font-size: 1rem;
color: #fff;
border-radius: .1875rem;
display: inline-block;
cursor: pointer;
-webkit-user-select: none;
user-select: none;
}
.button:not(#new-quote):hover {
opacity: .8 !important;
}
.button:not(#new-quote) {
min-width: 1rem;
min-height: 1rem;
}
.button i {
vertical-align: middle;
}
#new-quote {
white-space: nowrap;
writing-mode: vertical-lr;
height: 50%;
border-top-left-radius: 0;
border-bottom-left-radius: 0;
vertical-align: middle;
background: #fff !important;
margin: 0;
position: relative;
right: 0.25625rem;
color: #333;
visibility: hidden;
}
#new-quote:before {
content: "";
position: absolute;
height: 100%;
width: 0.0625rem;
bottom: 0;
left: 0;
visibility: hidden;
-webkit-transform: scaleY(0);
transform: scaleY(0);
-webkit-transition: all .3s ease-in-out;
transition: all .3s ease-in-out;
}
#new-quote:hover:before {
visibility: visible;
-webkit-transform: scaleY(1);
transform: scaleY(1);
}
footer {
font-size: 0.85rem;
margin-bottom: 1rem;
}
footer a {
text-decoration: none;
color: #fff;
position: relative;
}
footer a:before {
content: "";
position: absolute;
width: 100%;
height: .0625rem;
bottom: 0;
left: 0;
background: #fff;
visibility: hidden;
-webkit-transform: scaleX(0);
transform: scaleX(0);
-webkit-transition: all .3s ease-in-out 0s;
transition: all .3s ease-in-out 0s;
}
footer a:hover:before {
visibility: visible;
-webkit-transform: scaleX(1);
transform: scaleX(1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="v-wrap">
<div class="quote-container" style="">
<div class="quote-text">
</div>
<div class="quote-author"></div>
<a id="tweet-quote" class="button"><i class="fa fa-twitter"></i></a>
<a id="tumblr-quote" class="button"><i class="fa fa-tumblr"></i></a>
</div>
<div id="new-quote" class="button">New quote</div>
<footer>
Created by LukasLSC
</footer>
</div>
Code output:
As you can see, ajax wasn't success
Uncaught TypeError: callback is not a function and Uncaught TypeError: Cannot read property 'text' of undefined (only in the stack snippet).
I found out this error disappears if I remove the getQuote(); function call. However, I need to call it, overwise, my project won't work. I also tried to use return $.ajax but there was a return quote line so I couldn't use it. The full code can be found here on codepen: https://codepen.io/Kestis500/pen/ZvyxKB?editors=0110.
Then I switched to another method using jQuery promises and used information in this thread: https://stackoverflow.com/a/40658281/8889739. Full code: https://codepen.io/Kestis500/pen/qpjxoq?editors=0110.
var MyFirstFunction = function() {
var getNewQuote = function(callback) {
var quote = {};
setTimeout(function() {
quote.text = 'Example';
quote.author = 'Example';
return quote;
}, 4000);
};
}
var MySecondFunction = function() {
console.log("DONE");
var getRandomColor = function() {
var colors = [
"#ff9966",
"#7f00ff",
"#396afc",
"#0cebeb",
"#06beb6",
"#642b73",
"#36d1dc",
"#cb356b",
"#3a1c71",
"#ef3b36",
"#159957",
"#000046",
"#007991",
"#56ccf2",
"#f2994a",
"#e44d26",
"#4ac29a",
"#f7971e",
"#34e89e",
"#6190e8",
"#3494e6",
"#ee0979"
],
randomNumber = Math.floor(Math.random() * colors.length);
return colors[randomNumber];
};
var updateText = function($t, qt) {
var twitter = "https://twitter.com/intent/tweet?hashtags=quotes&related=freecodecamp&text=";
twitter += '"' + qt.text + '" ';
twitter += qt.author;
var tumblr = "https://www.tumblr.com/widgets/share/tool?posttype=quote&tags=quotes,freecodecamp&caption=";
tumblr += qt.author;
tumblr += "&content=";
tumblr += qt.text;
tumblr += "&canonicalUrl=https%3A%2F%2Fwww.tumblr.com%2Fbuttons&shareSource=tumblr_share_button";
var $icon = $("<i class='fa fa-quote-left'>")
.prop("aria-hidden", true);
$t.find(".quote-text").html("").append($icon, qt.text);
$t.find(".quote-author").html("- " + qt.author);
$("#tweet-quote").attr("href", twitter);
$("#tumblr-quote").attr("href", tumblr);
};
var calcNewHeight = function(q) {
var $temp = $("<div>", {
class: "quote-container temp",
}).appendTo($("body"));
$temp.append($("<div>", {
class: "quote-text"
}), $("<div>", {
class: "quote-author"
}));
updateText($temp, q);
var h = $temp.height() + 40;
$temp.remove();
return h;
};
var changeColor = function(newColor) {
$("body, .button:not(#new-quote)").animate({
backgroundColor: newColor
});
$("#new-quote").animate({
color: newColor
});
$(".quote-text, .quote-author").css("color", newColor);
if ($("#modStyle").length === 0) {
$("head").append(
"<style id='modStyle'>#new-quote:before {background:" + newColor + ";}</style>"
);
} else {
$("head style#modStyle").html("#new-quote:before {background:" + newColor + ";}");
}
};
var getQuote = function() {
var nq, nc, nh = 0;
nq = getNewQuote();
nc = getRandomColor();
nh = calcNewHeight(nq);
$(".quote-container").children().css("opacity", 0);
changeColor(nc);
$(".quote-container, #new-quote").animate({
height: nh,
}, {
duration: 1000,
queue: false
});
$(".quote-container").animate({
padding: "2.5em"
}, {
duration: 1000,
queue: false
});
$("#new-quote").animate({
padding: "2.5em .75em"
}, {
duration: 1000,
queue: false
});
updateText($(".quote-container"), nq);
$(".quote-container").children().fadeTo(750, 1);
};
$("#new-quote").on("click", getQuote);
$(".quote-container, #new-quote").css({
visibility: "visible",
height: 0
});
$("#new-quote").css("padding", "0 .75em");
getQuote();
}
MyFirstFunction().done(MySecondFunction);
html,
body {
height: 100%;
width: 100%;
}
body {
margin: 0;
padding: 0;
background: #333;
color: #333;
font-family: sans-serif;
}
.v-wrap {
height: 100%;
text-align: center;
}
.v-wrap:before {
content: "";
display: inline-block;
vertical-align: middle;
width: 0;
height: 100%;
}
.quote-container {
width: 31.25rem;
background: #fff;
margin: 0;
display: inline-block;
vertical-align: middle;
border-radius: 0.1875rem;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
visibility: hidden;
padding: 0 2.5rem;
}
.quote-text {
font-size: 1.625rem;
}
.quote-text i {
margin-right: 0.6rem;
}
.quote-text p {
display: inline;
}
.quote-author {
font-size: 1rem;
margin: 0 0.4rem 2rem 0;
text-align: right;
}
.button {
padding: 0.75rem;
text-align: center;
font-size: 1rem;
color: #fff;
border-radius: .1875rem;
display: inline-block;
cursor: pointer;
-webkit-user-select: none;
user-select: none;
}
.button:not(#new-quote):hover {
opacity: .8 !important;
}
.button:not(#new-quote) {
min-width: 1rem;
min-height: 1rem;
}
.button i {
vertical-align: middle;
}
#new-quote {
white-space: nowrap;
writing-mode: vertical-lr;
height: 50%;
border-top-left-radius: 0;
border-bottom-left-radius: 0;
vertical-align: middle;
background: #fff !important;
margin: 0;
position: relative;
right: 0.25625rem;
color: #333;
visibility: hidden;
}
#new-quote:before {
content: "";
position: absolute;
height: 100%;
width: 0.0625rem;
bottom: 0;
left: 0;
visibility: hidden;
-webkit-transform: scaleY(0);
transform: scaleY(0);
-webkit-transition: all .3s ease-in-out;
transition: all .3s ease-in-out;
}
#new-quote:hover:before {
visibility: visible;
-webkit-transform: scaleY(1);
transform: scaleY(1);
}
footer {
font-size: 0.85rem;
margin-bottom: 1rem;
}
footer a {
text-decoration: none;
color: #fff;
position: relative;
}
footer a:before {
content: "";
position: absolute;
width: 100%;
height: .0625rem;
bottom: 0;
left: 0;
background: #fff;
visibility: hidden;
-webkit-transform: scaleX(0);
transform: scaleX(0);
-webkit-transition: all .3s ease-in-out 0s;
transition: all .3s ease-in-out 0s;
}
footer a:hover:before {
visibility: visible;
-webkit-transform: scaleX(1);
transform: scaleX(1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="v-wrap">
<div class="quote-container" style="">
<div class="quote-text">
</div>
<div class="quote-author"></div>
<a id="tweet-quote" class="button"><i class="fa fa-twitter"></i></a>
<a id="tumblr-quote" class="button"><i class="fa fa-tumblr"></i></a>
</div>
<div id="new-quote" class="button">New quote</div>
<footer>
Created by LukasLSC
</footer>
</div>
Code output:
It broke everything, the gray screen is because of the default codepen background
Uncaught TypeError: Cannot read property 'done' of undefined
You're using return from the asynchronous operation's callback. That just sets the return value of that callback (which is ignored in the case of setTimeout's or XHR's callback), it doesn't set the return value of your function.
You can't return the value from your function, which is why you're adding a callback. Instead:
var getNewQuote = function(callback) {
var quote = {};
setTimeout(function() {
quote.text = 'Example';
quote.author = 'Example';
callback(quote); // <====
}, 4000);
};
...and use the parameter of the callback, e.g.:
getNewQuote(function(quote) {
// Use quote here...
});
Live Example:
var getNewQuote = function(callback) {
var quote = {};
setTimeout(function() {
quote.text = 'Example';
quote.author = 'Example';
callback(quote); // <====
}, 1000);
};
getNewQuote(function(quote) {
console.log("quote:", quote);
});

Button is not displaying in FireFox

I am using a button that triggers 4-5 other buttons with animation. its working fine in Chrome but not in FireFox
I have used a fullscreen background video in my current project, with this button, but in firefox, when i inspect elements, it shows there, but the browser is not displaying the element at all.
inspiration taken by - http://codepen.io/phenax/
'use strict';
(function (document, win) {
var animation_time = 600;
var btn_move_limit = 30;
var item_showing = false;
var className = {
show_items: 'menu--list__show',
revolve: 'menu--list__revolve',
button_cross: 'bar__crossy'
};
var $el = {
toggle_btn: document.querySelector('.js-menu--toggle'),
menu_items: document.querySelector('.js-menu--list'),
items: document.querySelectorAll('.js-item')
};
var constrain = function constrain(val, lim) {
return val > lim ? lim : val < -lim ? -lim : val;
};
var setButtonPosition = function setButtonPosition(left, top) {
$el.toggle_btn.style.left = constrain(left, btn_move_limit) + 'px';
$el.toggle_btn.style.top = constrain(top, btn_move_limit) + 'px';
};
var showAllItems = function showAllItems() {
var item_menu = $el.menu_items.classList;
item_menu.add(className.show_items);
setTimeout(function () {
item_menu.add(className.revolve);
$el.toggle_btn.classList.add(className.button_cross);
item_showing = true;
}, animation_time);
};
var hideAllItems = function hideAllItems() {
var item_menu = $el.menu_items.classList;
item_menu.remove(className.revolve);
$el.toggle_btn.classList.remove(className.button_cross);
setTimeout(function () {
item_menu.remove(className.show_items);
item_showing = false;
setButtonPosition(0, 0);
}, animation_time);
};
var findPosRelative = function findPosRelative(e) {
e = e.pageX ? {
pageX: e.pageX,
pageY: e.pageY
} : e.touches[0];
var offset = {
x: win.innerWidth / 2,
y: win.innerHeight / 2
};
e.pageX = e.pageX - offset.x;
e.pageY = e.pageY - offset.y;
return e;
};
var menuBtnClickHandler = function menuBtnClickHandler() {
if (item_showing)
hideAllItems();
else
showAllItems();
};
var itemClick = function itemClick(e) {
var item_id = e.target.dataset.id;
console.log('Item ID: ' + item_id);
hideAllItems();
};
var mouseMoveMent = function mouseMoveMent(e) {
var left, top;
if (item_showing) {
e = findPosRelative(e);
left = 140 * e.pageX / win.innerWidth;
top = 140 * e.pageY / win.innerHeight;
} else {
left = 0;
top = 0;
}
setButtonPosition(left, top);
};
document.addEventListener('DOMContentLoaded', function () {
$el.toggle_btn.addEventListener('click', menuBtnClickHandler);
for (var i = 0; i < $el.items.length; i++) {
if (window.CP.shouldStopExecution(1)) {
break;
}
$el.items[i].addEventListener('click', itemClick);
}
window.CP.exitedLoop(1);
win.addEventListener('mousemove', mouseMoveMent);
win.addEventListener('touchmove', mouseMoveMent);
});
}(document, window));
.menu--toggle {
position: absolute;
width: 80px;
height: 80px;
border-radius: 50%;
transform: translateX(-50%);
border: none;
outline: none;
cursor: pointer;
left: 0;
top: 0;
color: #222;
z-index: 1;
background-image: url("../images/logo/logo.jpg");
background-position: center;
background-size: cover;
box-shadow: 0 0 0 rgba(204, 169, 44, 0.4);
}
.menu {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
margin-top: -80px;
filter: url("#svgFilter"); }
.menu .item {
position: absolute;
width: 80px;
height: 80px;
border-radius: 50%;
transform: translateX(-50%);
border: none;
outline: none;
cursor: pointer;
left: 0;
top: 0;
background-color: #FFEB3B;
color: #222; }
.menu .item {
transition: all 0.6s ease-in-out; }
.menu--toggle {
transition: all .2s linear; }
.menu--toggle .bar {
width: 20px;
height: 2px;
background-color: #222;
margin: 5px auto;
transition: all 0.6s ease-in-out; }
.menu--toggle.bar__crossy .bar:nth-child(2) {
opacity: 0; }
.menu--toggle.bar__crossy .bar:nth-child(1) {
transform: translateY(7px) rotate(45deg); }
.menu--toggle.bar__crossy .bar:nth-child(3) {
transform: translateY(-7px) rotate(-45deg); }
.menu--list ul {
list-style-type: none;
padding: 0;
margin: 0; }
.menu--list li {
position: absolute;
width: 60px;
height: 80px;
transition: all 0.6s ease-in-out;
transform-origin: 0% 50%; }
.menu--list__show .item {
margin-left: 60px; }
.menu--list__revolve li:nth-child(1) {
transform: rotate(90deg); }
.menu--list__revolve li:nth-child(1) .item {
transform: rotate(270deg); }
.menu--list__revolve li:nth-child(2) {
transform: rotate(180deg); }
.menu--list__revolve li:nth-child(2) .item {
transform: rotate(180deg); }
.menu--list__revolve li:nth-child(3) {
transform: rotate(270deg); }
.menu--list__revolve li:nth-child(3) .item {
transform: rotate(90deg); }
.menu--list__revolve li:nth-child(4) {
transform: rotate(360deg); }
.menu--list__revolve li:nth-child(4) .item {
transform: rotate(0deg); }
<div class="menu">
<nav class="menu--list js-menu--list">
<ul>
<li><button type="button" onClick="window.open('https://www.facebook.com/themadhousecafe', '_blank')" class="fa fa-facebook item js-item" data-id="1"></button></li>
<li><button type="button" onClick="window.open('http://blog.nomadbaker.com/', '_blank')" class="fa item js-item" data-id="2">Blog</button></li>
<li><button type="button" onClick="window.open('#', '_blank')" class="item js-item" data-id="3">Menu</button></li>
<li><button type="button" onClick="window.open('#', '_blank')" class="fa fa-phone item js-item" data-id="4"></button></li>
</ul>
</nav>
<button type="button" class='logo_button menu--toggle js-menu--toggle'>
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
</button>
</div>

Categories