0

So I'm building a Rails6 with Vue/Webpack app. What I'm trying to do is change multiple components within my navbar on page scroll.

Everything is working exceptionally well, except for my nav-links Home, About ect..

rightn now when I attempt to do getElementsByClassName('navlinks') on scroll nothing happens and I'm getting this error in my console Navbar.vue:95 Uncaught TypeError: Cannot read property 'contains' of undefined

I am new to Vue and JS so I am thinking im missing something small but I can not for the life of me figure this out.

here are my nav-links:

<Navbar>
  <%= link_to "Home", root_path, class: "navlinks sm:inline-block sm:mt-0", slot: "nav-link" %>
  <%= link_to "About", about_path, class: "navlinks sm:inline-block sm:mt-0", slot: "nav-link" %>
  <%= link_to "Features", features_path, class: "navlinks sm:inline-block sm:mt-0", slot: "nav-link" %>
  <%= link_to "Pricing", pricing_path, class: "navlinks sm:inline-block sm:mt-0", slot: "nav-link" %>
  <%= link_to "Contact", contact_path, class: "navlinks sm:inline-block sm:mt-0", slot: "nav-link" %>
</Navbar>

and this is the mounted function in my Vue Template:

mounted () {
    this.$nextTick(function(){
      window.addEventListener("scroll", function(){
        var navbar = document.getElementsByClassName("navlinks");
        var nav_classes = navbar.classList;
        if(document.documentElement.scrollTop >= 150) {
          if (nav_classes.contains("scrollLink") === false) {
            nav_classes.toggle("scrollLink");
          }
        }
        else {
          if (nav_classes.contains("scrollLink") === true) {
            nav_classes.toggle("scrollLink");
          }
        }
      })
    })
}

Please let me know if you need anymore information. Like I said all the other changes are all working, Im just getting the above error while trying to target multiple links to update their styles on scroll.

Shawn Wilson
  • 1,311
  • 14
  • 40
  • Possible duplicate of [What do querySelectorAll and getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) – Phil Oct 17 '19 at 22:49
  • TL;DR: `getElementsByClassName` returns a `NodeList`, not an individual node. You need to iterate it or select individual nodes out of it – Phil Oct 17 '19 at 22:56

0 Answers0