I'm using HTML/CSS and vanilla JS. I'm trying to create a simple carousel. However, whenever I click the 'next' button, the following slides show up under the last one. I'm not sure why this is happening. Code snippets are below. Can someone explain why this is happening?
By the way, I have not optimized this page for media queries yet, so it might look a little weird on smaller screens.
const buttons = document.querySelectorAll("[data-carousel-btn]");
buttons.forEach((button) => {
button.addEventListener("click", () => {
const offset = button.dataset.carouselBtn === "next" ? 1 : -1;
const slidesContainer = button
.closest("[data-carousel]")
.querySelector("[data-carousel-slides");
const slides = slidesContainer.querySelectorAll("[data-carousel-slide]");
const activeSlide = slidesContainer.querySelector("[data-active]");
const activeSlideIndex = [...slides].indexOf(activeSlide);
const nextSlideIndex = activeSlideIndex + offset;
if (nextSlideIndex < 0) {
slides[slides.length + nextSlideIndex].dataset.active = true;
return delete activeSlide.dataset.active;
}
if (nextSlideIndex >= slides.length) {
slides[0].dataset.active = true;
return delete activeSlide.dataset.active;
}
slides[nextSlideIndex].dataset.active = true;
return delete activeSlide.dataset.active;
});
});
.carouselContainer {
width: 1000px;
height: 500px;
position: relative;
display: flex;
justify-content: center;
border-style: dashed;
border-color: #010043;
}
.carouselContainer>ul {
padding: 0;
margin: 0;
list-style: none;
}
.slide {
display: flex;
width: 400px;
height: 500px;
justify-content: center;
align-items: center;
inset: 0;
opacity: 0;
transition-property: opacity;
transition-duration: 200ms;
transition-timing-function: ease-in-out;
transition-delay: 200ms;
border-style: dashed;
border-color: var(--magenta6);
}
.slide[data-active] {
opacity: 1;
z-index: 1;
transition-delay: 0ms;
}
.slideContent {
display: flex;
justify-content: space-between;
align-items: center;
flex-direction: column;
width: 300px;
height: 425px;
border-style: dashed;
border-color: #010043;
}
.slideContent .slideImg {
margin: 0;
width: 200px;
height: 200px;
border-radius: 100px;
z-index: 10px;
}
.slideContent .slideTxt {
border: magenta;
border-style: dashed;
height: 500px;
}
.carousel-button {
position: absolute;
background: none;
border: none;
outline: none;
font-size: 4rem;
top: 50%;
transform: translateY(-50%);
z-index: 2;
color: rgba(255, 255, 255, 0.5);
cursor: pointer;
padding: 0 0.5rem;
border-radius: 0.25rem;
background-color: rgba(0, 0, 0, 0.1);
transition: 0.5s;
}
.carousel-button:hover,
.carousel-button:focus {
background-color: rgba(0, 0, 0, 0.3);
color: #fff;
}
.carousel-button[data-carousel-btn="prev"] {
left: 1rem;
}
.carousel-button[data-carousel-btn="next"] {
right: 1rem;
}
<section class="row4 animateOnScroll" style="margin: 0 100px 100px 100px;">
<h2>don't just take it from us!</h2>
<div class="carouselContainer" data-carousel>
<button class="carousel-button" data-carousel-btn="prev">
❮
</button>
<button class="carousel-button" data-carousel-btn="next">
❯
</button>
<div class="carouselSlides">
<ul data-carousel-slides>
<li class="slide" data-carousel-slide data-active>
<div class="slideContent">
<div>
<img class="slideImg" src="./assets/imgPlaceholder.jpg">
</div>
<div class="slideTxt">
<div class="slideDesc">
<p style="color:black;">hello</p>
</div>
</div>
</div>
</li>
<li class="slide" data-carousel-slide>
<div class="slideContent">
<div>
<img class="slideImg" src="./assets/imgPlaceholder.jpg">
</div>
<div class="slideTxt">
<div class="slideDesc">
<p style="color:black;">hello</p>
</div>
</div>
</div>
</li>
<li class="slide" data-carousel-slide>
<div class="slideContent">
<div>
<img class="slideImg" src="./assets/imgPlaceholder.jpg">
</div>
<div class="slideTxt">
<div class="slideDesc">
<p style="color:black;">hello</p>
</div>
</div>
</div>
</ul>
</div>
</div>
</section>
part of your problem is your ul element is unstyled, its child li elements are going to stack as they normally do on top of each other. giving the ul element display: flex; will put your li's side by side.
If I were you, I would review each nested element of my tree and figure out its purpose, then remove it if not necessary. for example, div.carouselSlides does not seem like its serving any purpose that the ul could not do itself, at least in this small example.
Also, looking at an established project for implementation ideas (or just using it) might be a good idea . https://swiperjs.com/ is very established with powerful config options
Basically there should be 2 containers:
The element that is the parent of the <button>s and the "frame" that holds each slide. In the example it is article.box.
The element that is the parent of each div.slide in the example is section.frame.
Each container should be position: relative and all children of said containers should be position: absolute. Doing so will:
provide precision positioning of the <button>s and section.frame within the perimeters of article.box
allow all div.slide to hide underneath the visible layers (z-index:0+) with z-index: -1 and be visible with .active class at z-index: 1.
The JavaScript is optional, it's just written better but function should be basically the same.
View in full page mode, the image placeholder service does not have dynamic images.
const data = [
{img:"https://placem.at/people?random=1", cap:"People 1"},
{img:"https://placem.at/places?random=1", cap:"Places 2"},
{img:"https://placem.at/things?random=1", cap:"Things 3"}
];
const slides = genSlides(data);
const box = document.querySelector('.box')
const buttons = box.querySelectorAll("button");
buttons.forEach((button) => {
button.addEventListener("click", function(event) {
const offset = button.classList.contains("next") ? 1 : -1;
const active = box.querySelector(".active");
const actIdx = slides.indexOf(active);
const nextIdx = actIdx + offset;
active.classList.remove("active");
if (nextIdx < 0) {
return slides[slides.length + nextIdx].classList.add("active");
}
if (nextIdx >= slides.length) {
return slides[0].classList.add("active");
}
return slides[nextIdx].classList.add("active");
});
});
function genSlides(array) {
const frame = document.querySelector(".frame");
array.forEach(slide => {
frame.insertAdjacentHTML("beforeend", `
<div class="slide">
<figure>
<img src="${slide.img}" width="480">
<figcaption class="cap">${slide.cap}</figcaption>
</figure>
</div>`);
});
const slides = Array.from(frame.querySelectorAll(".slide"));
slides[0].classList.add("active");
return slides;
}
.box {
display: flex;
justify-content: center;
align-items: center;
position: relative;
width: 96vw;
min-height: 96vh;
border: 3px dashed #000;
}
.frame {
display: flex;
flex-flow: column nowrap;
justify-content: center;
align-items: center;
/* The element that is the parent of all .slide should be relative so the
slides, which are absolute positioned, can sit within .frame's perimeter */
position: relative;
}
.slide {
display: flex;
width: 100%;
height: 100%;
justify-content: center;
align-items: center;
/* All slides should be out of normal flow */
position: absolute;
/* All slides should be in the layer "under" the visible layer (z-index: 0+) */
z-index: -1;
opacity: 0;
animation: opacity 0.7s ease-in;
}
.active {
opacity: 1;
z-index: 1;
}
figure {
display: flex;
flex-flow: column nowrap;
justify-content: center;
align-items: center;
max-height: 100%;
margin: 0;
padding: 0;
border-style: 1px dashed #000;
}
img {
object-fit: contain;
}
.cap {
min-width: 100%;
text-align: center;
white-space: pre;
}
button {
display: inline-flex;
justify-content: center;
align-items: center;
position: absolute;
top: 50%;
z-index: 2;
padding: 0 0.5rem;
border: none;
border-radius: 0.25rem;
outline: none;
font-size: 4rem;
color: rgba(255, 255, 255, 0.5);
background: none;
background-color: rgba(0, 0, 0, 0.1);
transform: translateY(-50%);
transition: 0.5s;
cursor: pointer;
}
button:hover,
button:focus {
color: #fff;
background-color: rgba(0, 0, 0, 0.3);
}
button:active {
color: rgba(0, 0, 0, 0.5);
background: none;
}
.prev {
left: 1rem;
}
.next {
right: 1rem;
}
<main>
<h2>Content Title</h2>
<article class="box">
<button class="prev">❮</button>
<button class="next">❯</button>
<section class="frame"></section>
</article>
</main>
Related
Just made a simple div slider with navigation arrows. The div slider works just fine, except, I want some sort of CSS styling to be applied to the arrows.
That is, when a user clicks the left or right arrow, up to the last item, apply CSS styling telling the user they've reached the end of the slider.
let buttonLeft = document.getElementById('slide_left')
let buttonRight = document.getElementById('slide_right')
let container = document.getElementById('slider')
buttonLeft.addEventListener('click', function() {
container.scrollLeft -= 90
})
buttonRight.addEventListener('click', function() {
container.scrollLeft += 90
})
body {
background-color: #555;
height: 100vh;
display: grid;
align-items: center;
justify-items: center;
font-family: 'Helvetica';
}
div#slide_wrapper {
width: 440px;
display: flex;
justify-content: space-between;
height: fit-content;
}
div#slider {
width: 350px;
display: flex;
height: fit-content;
flex-wrap: nowrap;
overflow: hidden;
}
div.thumbnail {
min-width: 80px;
min-height: 80px;
cursor: pointer;
display: grid;
place-items: center;
font-size: 30px;
}
div.thumbnail:not(:last-child) {
margin-right: 10px;
}
div.thumbnail:nth-child(1) {
background-color: darkturquoise;
}
div.thumbnail:nth-child(2) {
background-color: goldenrod;
}
div.thumbnail:nth-child(3) {
background-color: rebeccapurple;
}
div.thumbnail:nth-child(4) {
background-color: powderblue;
}
div.thumbnail:nth-child(5) {
background-color: firebrick;
}
div.thumbnail:nth-child(6) {
background-color: sienna;
}
div.thumbnail:nth-child(7) {
background-color: bisque;
}
div.thumbnail:nth-child(8) {
background-color: navy;
}
div#slide_wrapper>button {
height: fit-content;
align-self: center;
font-size: 24px;
font-weight: 800;
border: none;
outline: none;
}
div#slide_wrapper>button:hover {
cursor: pointer;
}
<div id="slide_wrapper">
<button id="slide_left" class="slide_arrow">❮</button>
<div id="slider">
<div class="thumbnail active">1</div>
<div class="thumbnail">2</div>
<div class="thumbnail">3</div>
<div class="thumbnail">4</div>
<div class="thumbnail">5</div>
<div class="thumbnail">6</div>
<div class="thumbnail">7</div>
<div class="thumbnail">8</div>
</div>
<button id="slide_right" class="slide_arrow">❯</button>
</div>
Simply check to see if you need to disable each button based on the position of the scroll. Then if there is a need to disable a button, add the disabled class to the button, otherwise remove it.
Future enhancements.
Remove the hardcoded 360 value for the scroll end. This should be calculated from the size of the carousel items and the width of the viewport.
Allow more than one carousel to work with the same code. This could be achieved by using a javascript class that would hold the elements inside an object, separate from other carousels.
See the demo:
let buttonLeft = document.getElementById('slide_left')
let buttonRight = document.getElementById('slide_right')
let container = document.getElementById('slider')
let checkScroll = function() {
if (container.scrollLeft <= 0)
buttonLeft.classList.add("disabled");
else
buttonLeft.classList.remove("disabled");
if (container.scrollLeft >= 360)
buttonRight.classList.add("disabled");
else
buttonRight.classList.remove("disabled");
}
checkScroll();
buttonLeft.addEventListener('click', function() {
container.scrollLeft -= 90;
checkScroll();
})
buttonRight.addEventListener('click', function() {
container.scrollLeft += 90;
checkScroll();
})
body {
background-color: #555;
height: 100vh;
display: grid;
align-items: center;
justify-items: center;
font-family: 'Helvetica';
}
div#slide_wrapper {
width: 440px;
display: flex;
justify-content: space-between;
height: fit-content;
}
div#slider {
width: 350px;
display: flex;
height: fit-content;
flex-wrap: nowrap;
overflow: hidden;
}
div.thumbnail {
min-width: 80px;
min-height: 80px;
cursor: pointer;
display: grid;
place-items: center;
font-size: 30px;
}
div.thumbnail:not(:last-child) {
margin-right: 10px;
}
div.thumbnail:nth-child(1) {
background-color: darkturquoise;
}
div.thumbnail:nth-child(2) {
background-color: goldenrod;
}
div.thumbnail:nth-child(3) {
background-color: rebeccapurple;
}
div.thumbnail:nth-child(4) {
background-color: powderblue;
}
div.thumbnail:nth-child(5) {
background-color: firebrick;
}
div.thumbnail:nth-child(6) {
background-color: sienna;
}
div.thumbnail:nth-child(7) {
background-color: bisque;
}
div.thumbnail:nth-child(8) {
background-color: navy;
}
div#slide_wrapper>button {
height: fit-content;
align-self: center;
font-size: 24px;
font-weight: 800;
border: none;
outline: none;
}
div#slide_wrapper>button:hover {
cursor: pointer;
}
.slide_arrow.disabled {
opacity: 0.2;
cursor: auto !important;
}
<div id="slide_wrapper">
<button id="slide_left" class="slide_arrow">❮</button>
<div id="slider">
<div class="thumbnail active">1</div>
<div class="thumbnail">2</div>
<div class="thumbnail">3</div>
<div class="thumbnail">4</div>
<div class="thumbnail">5</div>
<div class="thumbnail">6</div>
<div class="thumbnail">7</div>
<div class="thumbnail">8</div>
</div>
<button id="slide_right" class="slide_arrow">❯</button>
</div>
a simple solution to this is to actually create a css class that defines the style of arrows when there are no more items and then just add/remove class based on current index of items
trying to do event 'scroll' and when in the callback function the record of position div only record of last position, i want to know if that div in the center target i want
const slide = document.querySelector(".slides")
slide.addEventListener('scroll', function(e) {
const slide2 = document.querySelector("#slide-2")
console.log(slide2.offsetLeft)
})
<div class="slider">
1
2
3
4
5
<div class="slides">
<div id="slide-1">1</div>
<div id="slide-2">2</div>
<div id="slide-3">3</div>
<div id="slide-4">4</div>
<div id="slide-5">5</div>
</div>
</div>
my goal here I want to know if a user on that div to Right and Left for my slider
so i can make active dots , i am trying to just use native javascript here :)
here is my Codepen example
https://codepen.io/lpllplp222/pen/BaRvwKm
I have used jQuery to achieve the same.
position() function from the jQuery provides the current position of an element from its top and left, I am using the left value to calculate the current active element and get its index, thereby providing an active class to the corresponding dot.
const slide = document.querySelector(".slides")
$('#slider-dots a').on('click', function(event) {
event.stopPropagation();
})
slide.addEventListener('scroll', function(e) {
var scrollLeft = $('#slides-wrapper').scrollLeft();
var currIndex = -1;
$('#slider-dots a').removeClass('active');
for(var i = 0; i<$('#slides-wrapper div').length; i++) {
if($($('#slides-wrapper div')[i]).position().left >= 0 && currIndex === -1) {
currIndex = i;
}
}
$($('#slider-dots a')[currIndex]).addClass('active');
})
* {
box-sizing: border-box;
}
.slider {
width: 400px;
text-align: center;
overflow: hidden;
}
.slides {
display: flex;
overflow-x: auto;
scroll-snap-type: x mandatory;
scroll-behavior: smooth;
-webkit-overflow-scrolling: touch;
/*
scroll-snap-points-x: repeat(300px);
scroll-snap-type: mandatory;
*/
}
.slides::-webkit-scrollbar {
width: 10px;
height: 10px;
}
#slider-dots a.active {
color: violet;
background-color: #000;
}
.slides::-webkit-scrollbar-thumb {
background: black;
border-radius: 10px;
}
.slides::-webkit-scrollbar-track {
background: transparent;
}
.slides > div {
scroll-snap-align: start;
flex-shrink: 0;
width: 300px;
height: 200px;
margin-right: 50px;
border-radius: 10px;
background: #eee;
transform-origin: center center;
transform: scale(1);
transition: transform 0.5s;
position: relative;
display: flex;
justify-content: center;
align-items: center;
font-size: 100px;
}
.slides > div:target {
/* transform: scale(0.8); */
}
.author-info {
background: rgba(0, 0, 0, 0.75);
color: white;
padding: 0.75rem;
text-align: center;
position: absolute;
bottom: 0;
left: 0;
width: 100%;
margin: 0;
}
.author-info a {
color: white;
}
img {
object-fit: cover;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.slider > a {
display: inline-flex;
width: 1.5rem;
height: 1.5rem;
background: white;
text-decoration: none;
align-items: center;
justify-content: center;
border-radius: 50%;
margin: 0 0 0.5rem 0;
position: relative;
}
.slider > a:active {
top: 1px;
}
.slider > a:focus {
background: #000;
}
/* Don't need button navigation */
#supports (scroll-snap-type) {
.slider > a {
display: none;
}
}
html,
body {
height: 100%;
overflow: hidden;
}
body {
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(to bottom, #74abe2, #5563de);
font-family: "Ropa Sans", sans-serif;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="slider" id='slider-dots'>
1
2
3
4
5
<div id='slides-wrapper' class="slides">
<div id="slide-1">
1
</div>
<div id="slide-2">
2
</div>
<div id="slide-3">
3
</div>
<div id="slide-4">
4
</div>
<div id="slide-5">
5
</div>
</div>
</div>
document.querySelectorAll('.sidebarCategory').forEach(el =>{
el.addEventListener('click', e =>{
let sub = el.nextElementSibling
if(sub.style.maxHeight){
el.classList.remove('opened')
sub.style.maxHeight=null
}
else{
document.querySelectorAll('.sidebarSubcategories').forEach(element => {
element.style.maxHeight=null
element.previousElementSibling.classList.remove('opened')
})
el.classList.add('opened')
sub.style.maxHeight = sub.scrollHeight + "px";
}
})
})
document.querySelectorAll('.sidebarSubcategories > div:not(.sidebarSubSubcategories)').forEach(el =>{
el.addEventListener('click', e =>{
let sub = el.nextElementSibling
if(sub!=null && sub.classList.contains('sidebarSubSubcategories'))
{
if(sub.style.maxHeight){
sub.style.maxHeight=null
sub.style.marginBottom=0
sub.style.padding='0 30px'
}
else{
sub.style.marginBottom='15px'
sub.style.padding='15px 30px'
sub.style.maxHeight = sub.scrollHeight + 30 + "px"
el.parentNode.style.maxHeight=el.parentNode.style.maxHeight.slice(0,el.parentNode.style.maxHeight.length-2) + sub.scrollHeight + 30 + "px"
}
}
})
})
.main{
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
width: 400px;
height: 300px;
overflow-y: auto;
background-color: aquamarine;
}
.sidebarCategory{
color: white;
position: relative;
height: 60px;
min-height: 60px;
display: flex;
align-items: center;
justify-content: flex-start;
font-size: 20px;
flex-wrap: wrap;
font-weight: 600;
fill: white!important;
cursor: pointer;
padding-left: 15px;
transition: 0.4s;
}
.sidebarCategory.opened{
background-color: rgba(3, 63, 109, 0.588);
}
.sidebarSubcategories{
max-width: 100%;
position: relative;
background-color: rgba(3, 63, 109, 0.588);
max-height: 0;
transition: 0.4s;
overflow-y: hidden;
}
.sidebarSubcategories > div:not(.sidebarSubSubcategories){
max-height: 45px;
/* height: 45px; */
position: relative;
min-height: 45px;
color: white;
cursor: pointer;
overflow-y: hidden;
display: flex;
align-items: center;
justify-content: flex-start;
flex-wrap: wrap;
padding: 0 30px;
border-bottom: 1px solid var(--blue);
}
.sidebarSubSubcategories{
max-height: 0;
overflow-y: hidden;
transition: 0.4s;
background-color: white;
border-radius: 5px;
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
margin: 0 15px;
}
.sidebarSubSubcategories > div{
cursor: pointer;
transition: 0.2s;
display: flex;
justify-content: center;
border-radius: 5px;
align-items: center;
padding: 10px;
width: 49%;
}
.sidebarSubSubcategories > div:hover{
background-color: #f3f3f3;
}
<body>
<div class="main">
<div class="sidebarCategory">
Lorem ipsum dolor sit amet.
</div>
<div class="sidebarSubcategories">
<div>
Subcategory
</div>
<div class="sidebarSubSubcategories">
<div>Sub Subcategory</div>
<div>Sub Subcategory</div>
<div>Sub Subcategory</div>
<div>Sub Subcategory</div>
</div>
<div>
Subcategory
</div>
<div>
Subcategory
</div>
<div>
Subcategory
</div>
</div>
</div>
</body>
See the code, the first drop-down is not closing smoothly if I interact with the second drop-down menu.
I am changing the max-height property to create an accordion. I have placed another accordion inside the accordion. But when I interact with the inside accordion, the out-side accordion's transition does not work.
Looks like the issue is this line
el.parentNode.style.maxHeight.slice(0,el.parentNode.style.maxHeight.length-2) + sub.scrollHeight...."
Your adding a string and number which will always concatinate so '123' + 4 = the string '1234'. You need to parse to an int (you also won't need to slice off the px)
//Instead of
el.parentNode.style.maxHeight.slice(0,el.parentNode.style.maxHeight.length-2)
//Do this
parseInt(el.parentNode.style.maxHeight)
I think the problem is that the sidebarSubcategories element has no defined height. It has a max-heigth of 0 and then it is set to null via JavaScript.
The default value of height is auto, so, when you set maxHeight to null, you are setting max-height to auto, and transitions don't work on auto values.
That's because the browser doesn't know which value to transition to.
If you really need this and you can't a priori set each sidebarSubcategories' height, you'll need to store the innerHeight of each sidebarSubcategories (when it's expanded) and applying it back when expanded again.
I am beginner level javascript developer. I have decide to make carousel by using pure Javascript. I successfully manage to slide the carousel. I have decided to make active dots(also clickable), i want the dots background colour change when slide happen and left-right button. I have created the dots but I don't know how to implement the dots in my slide function as well left and right button. Here is my code:
Also please explain me the logic. Thank you
const images = document.getElementById('imgs');
const allImages = document.querySelectorAll('#imgs img');
const leftBtn = document.getElementById('left');
const rightBtn = document.getElementById('right');
let index = 0;
function run() {
const dot = [...document.getElementsByClassName('star')];
index++;
if (index > allImages.length - 1) {
index = 0
dot.forEach(i => i.classList.add('active'))
}
imgs.style.transform = `translateX(${-index * 500}px)`
}
const dot = allImages.forEach(i => {
const elem = document.createElement('div');
elem.classList.add('star');
document.body.appendChild(elem)
})
let x = setInterval(run, 2000);
images.onmouseover = () => {
clearInterval(x)
}
images.onmouseout = () => {
x = setInterval(run, 2000);
}
*{
box-sizing: border-box;
}
body {
margin: 0;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.carousel {
overflow: hidden;
width: 500px;
height: 500px;
box-shadow: 2px 2px 5px rgba(0, 0, 0, .3);
border-radius: 5px;
}
.image-container {
display: flex;
transition: transform 300ms linear;
transform: translateX(0);
}
img {
width:500px;
height: 500px;
object-fit: cover;
}
.star{
cursor: pointer;
height: 15px;
width: 15px;
margin: 0 10px;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
background-color: #eeeeee;
}
.star.active{
background-color: red;
}
button{
cursor: pointer;
position: relative;
font-size: 18px;
transition: 0.6s ease;
user-select: none;
height: 50px;
width: 40px;
display: flex;
justify-content: center;
align-items: center;
align-content: center;
top: calc(50% - 25px);
}
button:hover {
background-color: rgba(0,0,0,0.8);
};
button.left {
border-radius: 3px 0 0 3px;
right: 0;
}
button.left {
border-radius: 3px 0 0 3px;
left: 0;
}
<button id="left">❮</button>
<button id="right">❯</button>
<div class="carousel">
<div class="image-container" id="imgs" >
<img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
<img src="https://images.unsplash.com/photo-1516026672322-bc52d61a55d5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
<img src="https://images.unsplash.com/photo-1573081586928-127ecc7948b0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
<img src="https://images.unsplash.com/flagged/photo-1572850005109-f4ac7529bf9f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
</div>
</div>
You were close to the result. In your run function, you just have to change the class of the current active dot and set the new one to active. I renamed your dot variable to dots for the sake of comprehension.
function run() {
const dots = [...document.getElementsByClassName('star')];
index++;
if (index > allImages.length - 1) {
index = 0
}
dots.forEach((dot, i) => {
if (dot.classList.contains('active')) dot.classList.remove('active');
if (i === index) dot.classList.add('active'));
}
imgs.style.transform = `translateX(${-index * 500}px)`
}
JoinVideoCallButton
Hi!
I simply wonder if anyone here have any idea how to make such a hover effect that could be used for such double option buttons or navbars etc.
I have the css and html code for it but I have no idea how to make the effect work. Also, I wonder if it is possible without the use of Jquery?
body {
background-size: 100%;
margin: 0px;
background-color: gray;
}
.joinVideoCallButton-2Pohj0 {
-ms-flex-align: center;
-ms-flex-pack: center;
-webkit-box-align: center;
-webkit-box-pack: center;
-webkit-box-sizing: border-box;
align-items: center;
background-color: #43b581;
border-radius: 3px;
box-sizing: border-box;
cursor: pointer;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
height: 36px;
justify-content: center;
overflow: hidden;
padding: 0 14px;
position: relative;
}
.joinVideoCallButton-2Pohj0 .underlay-1LCk7B {
-webkit-transition: opacity .1s ease;
background-color: #69c49a;
border-radius: 3px;
bottom: 0;
left: 0;
margin: 2px;
position: absolute;
top: 0;
transition: opacity .1s ease;
width: 50%;
flex: 1 1 auto;
}
.joinVideoCallButton-2Pohj0 .inner-1e8n63 {
cursor: pointer;
z-index: 1;
flex: 1 1 auto;
}
.flex-lFgbSz:first-child, .horizontal-2BEEBe>.flexChild-1KGW5q:first-child {
margin-left: 0;
}
.flex-lFgbSz, .horizontal-2BEEBe>.flexChild-1KGW5q {
margin-left: 10px;
margin-right: 10px;
}
.joinVideoCallButton-2Pohj0 .callDivider-_hMb9n {
background-color: #69c49a;
height: 20px;
margin: 0 2px;
opacity: .6;
width: 2px;
}
.joinVideoCallButton-2Pohj0 .icon-3tOP24 {
height: 16px;
width: 16px;
}
.joinVideoCallButton-2Pohj0 .buttonText-1b8lyZ {
color: #f6f6f7;
font-size: 14px;
margin-left: 8px;
margin-right: 8px;
text-transform: uppercase;
}
.wrapper-1XTKlU{
background-size:cover;
min-height:100vh;
overflow:hidden
}
.flexWrapper-1ztpWj{
height:100vh
}
.flex-3B1Tl4{
display:-webkit-box;
display:-ms-flexbox;
display:flex
}
.alignStart-pnSyE6{
-ms-flex-align:start;
-webkit-box-align:start;
align-items:flex-start
}
.alignEnd-3PVyen{
-ms-flex-align:end;
-webkit-box-align:end;
align-items:flex-end
}
.alignCenter-3VxkQP{
-ms-flex-align:center;
-webkit-box-align:center;
align-items:center
}
.alignStretch-1hwxMa{
-ms-flex-align:stretch;
-webkit-box-align:stretch;
align-items:stretch
}
.alignBaseline-4enZzv{
-ms-flex-align:baseline;
-webkit-box-align:baseline;
align-items:baseline
}
.justifyStart-2yIZo0{
-ms-flex-pack:start;
-webkit-box-pack:start;
justify-content:flex-start
}
.justifyEnd-1ceqOU{
-ms-flex-pack:end;
-webkit-box-pack:end;
justify-content:flex-end
}
.justifyCenter-29N31w{
-ms-flex-pack:center;
-webkit-box-pack:center;
justify-content:center
}
.justifyBetween-1d1Hto{
-ms-flex-pack:justify;
-webkit-box-pack:justify;
justify-content:space-between
}
.horizontal-2VE-Fw>.spacer-2Aeq3k,.horizontalReverse-k5PqxT>.spacer-2Aeq3k,.vertical-3X17r5>.spacer-2Aeq3k{
min-height:1px
}
.horizontal-2BEEBe>.flex-lFgbSz,.horizontal-2BEEBe>.flexChild-1KGW5q{
margin-left:10px;
margin-right:10px
}
.horizontal-2BEEBe>.flex-lFgbSz:first-child,.horizontal-2BEEBe>.flexChild-1KGW5q:first-child{
margin-left:0
}
.horizontal-2BEEBe>.flex-lFgbSz:last-child,.horizontal-2BEEBe>.flexChild-1KGW5q:last-child{
margin-right:0
}
<div class="flex-lFgbSz flex-3B1Tl4 horizontal-2BEEBe horizontal-2VE-Fw flex-3B1Tl4 directionRow-yNbSvJ justifyCenter-29N31w alignStretch-1hwxMa noWrap-v6g9vO private-channel-call-actions" style="">
<div class="joinVideoCallButton-2Pohj0">
<div class="underlay-1LCk7B" style="opacity: 1; transform: translateX(31.5781px);"></div>
<div class="flex-lFgbSz flex-3B1Tl4 horizontal-2BEEBe horizontal-2VE-Fw flex-3B1Tl4 directionRow-yNbSvJ justifyCenter-29N31w alignCenter-3VxkQP noWrap-v6g9vO inner-1e8n63" style="flex: 1 1 auto;">
<div class="flex-lFgbSz flex-3B1Tl4 horizontal-2BEEBe horizontal-2VE-Fw flex-3B1Tl4 directionRow-yNbSvJ justifyCenter-29N31w alignCenter-3VxkQP noWrap-v6g9vO callButton-205P-D" style="flex: 1 1 auto;"><img class="icon-3tOP24" src="http://discordapp.com/assets/0682cf612d4fed39efb57e0a1bcc8544.svg">
<div class="buttonText-1b8lyZ">Video</div>
</div>
<div class="callDivider-_hMb9n"></div>
<div class="flex-lFgbSz flex-3B1Tl4 horizontal-2BEEBe horizontal-2VE-Fw flex-3B1Tl4 directionRow-yNbSvJ justifyCenter-29N31w alignCenter-3VxkQP noWrap-v6g9vO callButton-205P-D" style="flex: 1 1 auto;">
<div class="buttonText-1b8lyZ">Voice</div><img class="icon-3tOP24" src="http://discordapp.com/assets/8b47456a037cc496c55ae8f871274018.svg"></div>
</div>
</div>
</div>
Part 1
The idea is fairly simple: you need to add an extra "hover box" element inside the button row, absolute position it, and finally just change the left value of the object according to the position of the cursor:
function relocateHoverBox(e) {
// Get all the needed values
// (idealy don't use as many variables)
let hoverBoxEl = e.target.closest(".btn-row").querySelector(".btn-row--hover-box");
let hoverBoxHalfWidth = hoverBoxEl.clientWidth / 2;
let containerX = e.target.closest(".btn-row").getBoundingClientRect().left;
let maxLeft = e.target.closest(".btn-row").clientWidth - hoverBoxEl.clientWidth;
let newLeftValue = e.pageX - containerX - hoverBoxHalfWidth;
// Apply new left value accordingly
if (newLeftValue >= 0) {
if (newLeftValue > maxLeft) {
hoverBoxEl.style.left = maxLeft + "px";
}
else {
hoverBoxEl.style.left = e.pageX - containerX - hoverBoxHalfWidth + "px";
}
}
else {
hoverBoxEl.style.left = 0 + "px";
}
}
// Set the hover box in the right position as soon as the mouse enters
const mouseoverHandler = function(e) {
relocateHoverBox(e);
}
// Update the hover box position
const mousemoveHandler = function(e) {
relocateHoverBox(e);
}
// Reset the hover box position
const mouseleaveHandler = function(e) {
e.target.closest(".btn-row").querySelector(".btn-row--hover-box").style.left = "";
}
document.getElementsByClassName("btn-row")[0].addEventListener('mousemove', mousemoveHandler);
document.getElementsByClassName("btn-row")[0].addEventListener('mouseenter', mouseoverHandler);
document.getElementsByClassName("btn-row")[0].addEventListener('mouseleave', mouseleaveHandler);
body {
margin: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background: #202225;
}
.btn-row {
display: flex;
justify-content: center;
align-items: center;
border-radius: 4px;
height: 48px;
background: #43b581;
position: relative;
}
.btn-row--hover-box {
width: 50%;
height: 44px;
border-radius: 2px;
position: absolute;
top: 50%;
left: 0;
transform: translateY(-50%);
}
.btn-row--hover-box:hover {
background: rgba(255, 255, 255, 0.25);
}
.btn {
background: transparent;
letter-spacing: .1rem;
padding: 0 1rem;
border: 0;
color: #fff;
height: 28px;
display: block;
font-weight: bold;
text-transform: uppercase;
}
<div class="btn-row">
<div class="btn-row--hover-box"></div>
<button class="btn">Option 1</button>
<button class="btn">Option 2</button>
</div>
Part 2
Also, I wonder if it is possible without the use of Jquery?
If by "Jquery" you actually mean the jQuery library, then just remember that it is a library, which means that it is only a collection of useful scripts written in a programming language, then since you can write your own scripts using that language, it is possible to do it without jQuery
If by "Jquery" you mean Javascript (the language in which jQuery is written), then it's not possible to do it without it, since you need it to follow the x-coordinate of the cursor.