1

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>
Reggio
  • 19
  • 6

1 Answers1

-1

Thanks, now it works, I just need to access to the ID of the slide dynamically...

Reggio
  • 19
  • 6
  • Hi Reggio, welcome to StackOverflow. To help people in future with the same problem, would you be able to edit your answer to include your solution? – Charlie Harding Jul 31 '19 at 09:05
  • And as for scrolling to the relevant section dynamically, you’ve hard-coded `section3` into your loop in the example, why not use `section${i+1}`? Or even better, wrap the slides in a container, and access them by index, rather than relying on numerical string IDs: `document.getElementById('slides').children[i]`. – Charlie Harding Jul 31 '19 at 09:10