1

I have a number of elements in my page that I give the class "page-link" and the attribute "dest='#some-id'".

Then I have this javascript snippet:

window.onload = function() {
    setPageLinks();
}

function setPageLinks() {
    const PAGE_LINKS = document.getElementsByClassName("page-link");
    for (let i = 0; i < PAGE_LINKS.length; i++) {
        PAGE_LINKS[i].addEventListener("click", function(event) {
            let linkTarget = event.target.getAttribute("dest");
            //alert(linkTarget);
            $('html, body').animate({
                scrollTop: $(linkTarget).offset().top
            }, 600);
        });
    }
}

It makes all the elements with class "page-link" scroll to the element with the ID specified in the "dest" attribute.

It's working fine with all my "page-link" elements, except for one that happens to be a button element. The getAttribute method on that one occasionally - and seemingly randomly - returns null when clicked. This doesn't happen in Firefox, but it happens in Chrome, Edge, and Opera.

This is my button element:

<button type="button" class="page-link" dest="#about">
    <span class="front-btn-text">View my work</span>
    <span class="front-btn-arrow"><i class="fas fa-arrow-right"></i></span>
</button>

Can anyone tell me why this error occurs, what to do about it (and possibly why it doesn't occur in Firefox?

Thanks!

Tor
  • 93
  • 6
  • Does it still happen when you use `const PAGE_LINKS = Array.from(document.getElementsByClassName("page-link"));` instead? `getElementsByClassName` returns an `HTMLCollection` which is a _live_ list; so when any `.page-link` element changes, `PAGE_LINKS` may be affected and mutate. – Sebastian Simon Jan 17 '19 at 10:19
  • @Xufox thanks for your input! Yes, it still produces the error when using your line instead. – Tor Jan 17 '19 at 10:25
  • If you click on one of the `` or `` elements, the `event.target` doesn't have a `dest` attribute. Use `this` or `event.currentTarget` instead. – Bergi Jan 17 '19 at 11:27
  • @Bergi thank you! Changing 'target' to 'currentTarget' seems to have fixed the issue. I'll have to read up on the difference between those. – Tor Jan 17 '19 at 12:05

0 Answers0