I've tried to move the slider depending on the element that was clicked, but I can't. I managed to get the width of the item to modify it with respect to the content. I hope you can help me, thanks in advance
let items = document.querySelectorAll('.menu-item-category'),
slider = document.querySelector('.slider')
items.forEach((item, e) => {
item.addEventListener('click', () => {
console.log(e)
let getWidth = item.offsetWidth
slider.style.width = getWidth + 'px'
})
})
.category-results {
display: flex;
align-items: center;
position: relative;
}.menu-item-category:nth-child(1), .menu-item-category:nth-child(2) {
margin-right: 25px;
}.menu-item-category {
color: #262626;
font-size: 1.3em;
text-transform: capitalize;
height: 100%;
display: flex;
align-items: center;
cursor: pointer;
transition: color 300ms ease-in-out;
}.slider {
position: absolute;
height: 3px;
background: red;
width: 39%;
bottom: 0;
display: block;
}
<div class="category-results">
<div class="menu-item-category active">trending</div>
<div class="menu-item-category">text too loooong</div>
<div class="menu-item-category">test3</div>
<div class="slider" style="width: 81px;"></div>
</div>
The code is correct, just need to move the slider below the menu item. You can do it this way:
Include that line below
slider.style.width = getWidth + 'px'
so that the slider moves as many pixels to the left as the item you clicked on.