so I want to make JS function, that adds random string from my array to HTML, then remove it and add another instead of it. My code now does everything I want to, it just doesn't remove past element and adds another one instead.
In other words - I just want a simple text slide.
MY HTML:
<section style="height: 100vh;" class="">
<div class="container pt-2 pb-2">
<div class="row">
<div class="col d-flex justify-content-center text-uppercase">
<div>
<h1>
Mes teikiame
</h1>
<div class="scroller">
<span>
</span>
</div>
<h1>
Paslaugas
</h1>
</div>
</div>
</div>
</div>
</section>
MY JS:
// Selecting elements
let scrollerSpan = document.querySelector('.scroller > span')
// Creating elements
let textInsideScroller = document.createElement('span')
// Class add
textInsideScroller.classList.add('text-inside-scroller')
// Function generating service name in random order for scroller
const dynamicServiceNames = () => {
const serviceNames = ['example1', 'example2', 'example3', 'example4', 'example5', 'example6', 'example7'];
const randomName = serviceNames[rand(0, serviceNames.length)];
textInsideScroller.append(randomName)
scrollerSpan.append(textInsideScroller)
};
// Executing my function
let i = 1;
setInterval(function()
{
dynamicServiceNames(i++);
}, 1000)
UPDATE: Tried to solve this issue by adding this to the function:
// Function generating service name in random order for scroller
const dynamicServiceNames = () => {
const serviceNames = ['grožio', 'voljerų gaminimo', 'apskaitos priežiūros', 'kasinėjimo', 'metinių ataskaitų teikimo', 'deklaracijų ruošimo', 'barščių virimo'];
const randomName = serviceNames[rand(0, serviceNames.length)];
textInsideScroller.append(randomName)
if (scrollerSpan.contains(textInsideScroller)){
scrollerSpan.remove(textInsideScroller)
}
else{
scrollerSpan.append(textInsideScroller)
}
};
But this didn't helped. Now the random string comes from array, but only one time -- I need to refresh the page in order to get another random string....
You could just update the innerHTML property of scrollerSpan with randomName.Also,I updated the rand function with Math.random to test this out.
// Selecting elements
let scrollerSpan = document.querySelector('.scroller > span')
// Function generating service name in random order for scroller
const dynamicServiceNames = () => {
console.log('inside function')
const serviceNames = ['example1', 'example2', 'example3', 'example4', 'example5', 'example6', 'example7'];
const randomName = serviceNames[Math.floor(Math.random()*serviceNames.length)];
scrollerSpan.innerHTML= `<span>${randomName}</span`;
};
// Executing my function
let i = 1;
setInterval(function()
{
console.log('in function')
dynamicServiceNames(i++);
}, 1000)
splice might be what you're looking for:
const array = [1, 2, 3];
array.splice(1, 1, 5);
// from index 1, remove 1 element, insert 5
console.log(array); // [1, 5, 3];