I am trying to make a little slide menu. Each slide is 100vh and I want to scroll to each slide with my menu.
I did the query and the listeners and now I try to make each click go to the right #slide.
The number of slides will be dynamic.
I am not a javascript superhero so I hope I started all good !
Thanks in advance for your help and advices.
let sections= document.querySelectorAll('.slide')
let nbrMenuLinks = sections.length;
for(i = 0; i < nbrMenuLinks; i++) {
const li = document.createElement('li');
li.className = 'scroll-item';
li.id = 'btn'+(i+1);
li.appendChild(document.createTextNode((i+1)));
document.querySelector('#slide-menu').appendChild(li);
li.addEventListener('click', ()=> {
window.scroll(0,findPos(document.getElementById(`slide3`)));
});
}
function findPos(obj) {
var curtop = 0;
if (obj.offsetParent) {
do {
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return [curtop];
}
}
<ul id="slide-menu"></ul>
<div id="slide1" class="slide">
<h2>Slide 1</h2>
</div>
<div id="slide2" class="slide">
<h2>Slide 2</h2>
</div>
<div id="slide3" class="slide">
<h2>Slide 3</h2>
</div>
<div id="slide4" class="slide">
<h2>Slide 4</h2>
</div>