K
K
Kryptonit2020-05-13 17:30:18
JavaScript
Kryptonit, 2020-05-13 17:30:18

How to implement this in pure JS?

Purpose: to implement anchor links on the page using JS. Here is the HTML:

<ul class = "list">
                    <li class="li active">главная</li>
                    <li class="li">навыки</li>
                    <li class="li">опыт</li>
                    <li class="li">портфолио</li>
                    <li class="li">контакты</li>
                </ul>


Here is the already written JS:
let li = document.querySelectorAll('.li');
    let ul = document.querySelector('.list');

// Определяю по какой ссылке был клик:

li.forEach(i => {
        i.addEventListener('click', function(){
            //Здесь нужно вызвать ф-ю для каждого элемента 
            
        });
    });
// Вот эта функция, переносящаяся на нужный блок

function ScrollTo(element){
        window.scroll({
            left: 0, 
            top: element.offsetTop,
            behavior: 'smooth'
        })
    }

You can just use If with ami, but I don't like that way.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Ukolov, 2020-05-13
@Kryptonit

Goal: implement anchor links
Step number 0 to achieve this goal is to actually use links in the markup, and specify the element ID as href. And then no if will be needed - it will be easy to get the id of the element, and by id already its own.
As a bonus, people with broken or disabled js will be able to use this menu and it will be possible to copy a direct link to a specific block.
But if you really want to break the standard scenario of using links on pages, because you "do not like their display in the address bar", you can achieve this through event.preventDefault().

B
Banan44, 2020-05-13
@Banan44

let ul = document.querySelector('.list');

// Определяю по какой ссылке был клик:


ul.addEventListener('click', data => {
    ScrollTo(data.target) // Дочерний элемент на который вы нажали в блоке
})
// Вот эта функция, переносящаяся на нужный блок

function ScrollTo(element){
    window.scroll({
        left: 0, 
        top: element.offsetTop,
        behavior: 'smooth'
    })
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question