I have a dynamic top bar on my WordPress website with 3 messages that appear in constant loop one after the other. The issue is that there is like 5 seconds of delay between the 3rd item(message) and the first item that appears again where there is no message shown in the top bar, it’s supposed to be a continuous flow.
This is the code that I use:
var topBarItems = document.querySelectorAll('.top-bar-item');
var currentItemIndex = 0;
function showNextItem() {
// Oculta el item actual
topBarItems[currentItemIndex].style.display = 'none';
// Mueve al siguiente item
currentItemIndex++;
// Si el índice supera el número de items, vuelve al primero
if (currentItemIndex >= topBarItems.length) {
currentItemIndex = 0;
}
// Muestra el siguiente item
topBarItems[currentItemIndex].style.display = 'flex';
// Configura el próximo ciclo
setTimeout(showNextItem, 2000);
}
// Inicializa el ciclo
showNextItem();
.top-bar {
background-color: #000;
height: 35px;
display: flex;
justify-content: center;
color: white;
}
.top-bar-wrap {
position: relative;
display: flex;
align-items: center;
}
.top-bar-item {
display: none;
align-items: center;
margin-right: 20px;
font-size: 12px;
font-weight: 500;
margin-bottom: 5px;
margin-top: 5px
}
.top-bar-item:first-child {
display: flex;
}
.top-bar-item img {
width: auto;
height: 25px;
margin-right: 15px;
}
.top-bar-item span {
margin-left: 10px;
font-size: 12px;
}
.top-bar-wrap .top-bar-item:not(:first-child) {
position: absolute;
left: -100%;
animation-name: move-left;
animation-duration: 10s;
animation-iteration-count: infinite;
animation-timing-function: linear;
}
.top-bar-wrap .top-bar-item:nth-child(2) {
animation-delay: 6s;
}
.top-bar-wrap .top-bar-item:nth-child(3) {
animation-delay: 12s;
}
@keyframes move-left {
from {
transform: translateX(0);
opacity: 1;
}
to {
transform: translateX(-100%);
opacity: 0;
}
}
@media only screen and (max-width: 768px) {
.top-bar {
height: 35px;
overflow: hidden;
}
.top-bar-content {
flex-wrap: wrap;
align-items: center;
}
.top-bar-item {
width: 100%;
display: flex;
align-items: center;
margin-right: 0;
margin-bottom: 5px;
margin-top: 8px;
font-size: 12px;
font-weight: 500;
line-height: 0px;
/* Añadido para alinear verticalmente el texto */
text-align: center;
}
.top-bar-item img {
width: auto;
height: 20px;
margin-right: 10px;
}
}
<div class="top-bar">
<div class="top-bar-content">
<div class="top-bar-item"><img src="https://picsum.photos/seed/78909812-1/200/300" alt="Envío gratis" /> Envío gratis por compras mayores a $200</div>
<div class="top-bar-item"><img src="https://picsum.photos/seed/78909812-2/200/300" alt="Entregas" /> Entregas de 5 - 7 días</div>
<div class="top-bar-item"><img src="https://picsum.photos/seed/78909812-3/200/300" alt="Devoluciones" /> Devoluciones gratis</div>
</div>
</div>