Nat
Nat

Reputation: 55

Javascript can't find element for collapsing header

My Javscript:

var navTop = document.getElementsByClassName('main-nav');
window.addEventListener('scroll', function() {
   if(window.pageYOffset > 100) {
     navTop.classList += ' .small';
   } else{
     navTop.classList = 'main-nav';
   };
});

The header:

<div>
  <header class='main-nav'>
    <nav>
      <ul>
        <a href='#aboutme'>
          <li>About Me</li>
        </a>
        <br>
        <a href='#projects'>
          <li>Projects</li>
        </a>
        <br>
        <a href='#experience'>
          <li>Experience</li>
        </a>
        <br>
        <a href='#contactme'>
          <li>Contact Me</li>
        </a>
        <br>
      </ul>
    </nav>
  </header>
</div>

I have the nav set to fixed, but the JavaScript isn't doing anything. Instead, it just shows a 'navTop is null' error every time I scroll down. Is there anything wrong with my syntax or logic that could be causing this? And if there is a better way to make a collapsing header, I'd be happy to hear it.

Upvotes: 0

Views: 58

Answers (2)

Satpal
Satpal

Reputation: 133453

As getElementsByClassName() returns HTMLCollection, you need to use elements using index and manipulate them. Here in example I have used 0 for first element.

Also as you are using classList, its methods needs to be used to manipulate CSS classes

var navTop = document.getElementsByClassName('main-nav');
window.addEventListener('scroll', function () {
    if (window.pageYOffset > 100) {
        navTop[0].classList.add('small')
    } else {
        navTop[0].classList.remove('small')
    };
});

You can also use toggle() method as suggested by @David

classList.toggle('small', window.pageYOffset > 100);

Upvotes: 2

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

Since you have only one element with class main-nav you can use querySelector() to get the reference of that element instead of using getElementsByClassName() which will return you the array of elements.

Change your code to:

var navTop = document.querySelector('.main-nav');
window.addEventListener('scroll', function () {
    if (window.pageYOffset > 100) {
        navTop.classList.add('small')
    } else {
        navTop.classList.remove('small')
    };
});

Upvotes: 1

Related Questions