I want to make a navigation, that looks like 1/5 then 2/5 then 3/5 and so on.
- the first digit is the number of the current page
- the second digit is the total number of pages
At the moment, everything works, except for the number of the current page: it is created, but the old one is not deleted.
Thank you in advance!
// slides
let item = document.querySelectorAll('.item');
let btn = document.querySelector('.btn');
let el_active;
let current = document.querySelector('.current');
let total = document.querySelector('.total');
function navigate() {
for (let i = 0, length = item.length; i < length; i ) {
if (item[i].classList.contains('active')) {
el_active = i;
current.append(i 2);
break;
}
}
item.forEach(function(tab) {
tab.classList.remove('active');
});
if ((el_active 1) === item.length) {
item[0].classList.add('active');
} else {
item[el_active 1].classList.add('active');
}
}
btn.addEventListener('click', function() {
navigate();
sliceAll()
});
let all = item.length;
total.append(all);
.item {
display: none;
}
.item.active {
display: block;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div >
<div >111</div>
<div >222</div>
<div >333</div>
<div >444</div>
<div >555</div>
</div>
<br>
<div >
<span >1</span> /
<span ></span>
</div>
<br>
<button type="button">Next</button>
</body>
</html>
CodePudding user response:
You need to use textContent
instead of append
, as append will add but will not reset the old value.
// slides
let item = document.querySelectorAll('.item');
let btn = document.querySelector('.btn');
let el_active;
let current = document.querySelector('.current');
let total = document.querySelector('.total');
function navigate() {
for (let i = 0, length = item.length; i < length; i ) {
if (item[i].classList.contains('active')) {
el_active = i;
current.textContent = (i 2);
break;
}
}
item.forEach(function(tab) {
tab.classList.remove('active');
});
if ((el_active 1) === item.length) {
item[0].classList.add('active');
} else {
item[el_active 1].classList.add('active');
}
}
btn.addEventListener('click', function() {
navigate();
sliceAll()
});
let all = item.length;
total.append(all);
.item {
display: none;
}
.item.active {
display: block;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div >
<div >111</div>
<div >222</div>
<div >333</div>
<div >444</div>
<div >555</div>
</div>
<br>
<div >
<span >1</span> /
<span ></span>
</div>
<br>
<button type="button">Next</button>
</body>
</html>