Mi objetivo es completar una página de destino única dinámica usando JavaScript. Ya se proporcionaron archivos HTML y CSS y logré crear una lista desordenada manipulando el DOM.
Lo que me atascó es: al hacer clic en un elemento del menú de navegación, el enlace debe desplazarse a la sección correspondiente. No puedo conseguir que esto funcione :/
A continuación se muestra el código JS hasta el momento.
/* Declare variables for the fictive document and menu list to retrieve and store variables as unordered list */ const container = document.createDocumentFragment(); const menuList = document.getElementsByTagName('section'); /* Function to create the navigation menu as a clickable link */ function navigationLink(id, name) { const navLink = `<a class = "menu__link" data-id=${id}">${name}</a>`; return navLink; } /* Function for the navigation list, built as an unordered list */ function createNavigation() { for (let i = 0; i < menuList.length; i++) { const newMenuListItem = document.createElement('li'); const menuListName = menuList[i].getAttribute('data-nav') const menuListID = menuList[i].getAttribute('id') newMenuListItem.innerHTML = navigationLink(menuListID, menuListName) container.appendChild(newMenuListItem); } /* Retrieve the id from the ul section to be added to the document fragment: container */ const navBarMenu = document.getElementById('navbar__list') navBarMenu.appendChild(container); } // Add class 'active' to section when near the top of viewport function setActiveClass() { for (let i = 0; i < menuList.length; i++) { if (isInViewport(menuList[i])) { menuList[i].classList.add("your-active-class"); } else { menuList[i].classList.remove("your-active-class"); } } }Para resolver el problema, busqué en otra pieza de código que no he podido funcionar correctamente.
function scrollToElement(event) { if (event.target.nodeName === 'A') { const menuListID = event.target.getAttribute('data-id'); const menu = document.getElementById(menuListID); menu.scrollIntoView({ behavior: "smooth" }); } } document.addEventListener('scroll', function () { setActiveClass(); }); const navBarMenu = document.getElementById('navbar__list') navBarMenu.addEventListener('click', function (event) { scrollToElement(event) })Puedes usar ancla para hacer esto. Esto hará tu vida más fácil que tratar de hacer esto en js.
Para usarlo, solo tiene que establecer una id para un nodo. Me gusta <div id="myFirstId"></div> y luego, establezca el href de su enlace en #myFirstId .
Si desea que su desplazamiento no sea instantáneo, puede agregar el scroll-behavior: smooth al elemento desplazable.
html { scroll-behavior: smooth; } #scrollable { overflow:auto; } #firstDiv { background-color: green; height: 700px } #secondDiv { background-color: yellow; height: 200px; } #thirdDiv { background-color: blue; height: 500px; } <a href="#firstDiv">firstDiv</a> <a href="#secondDiv">SecondDiv</a> <a href="#thirdDiv">thirdDiv</a> <div id="scrollable"> <div id="firstDiv"></div> <div id="secondDiv"></div> <div id="thirdDiv"></div> </div> Para su código, simplemente cambie esta línea <a class = "menu__link" data-id=${id}">${name}</a>
A este <a class="menu__link" href="#${id}">${name}</a>