0

Okay so below is just making the navigation shrink on scroll but noticed something. It still worked even though I put nav.classList when it should of been mainNav.classList. I then logged in the console and nav and mainNav return samething even though nav isn't declared. It happens with every ID in my HTML so if I only type in the id name without getElementById it would still log out the node. I'm a little confused on why this works. Is this new to ES6?

var mainNav = document.getElementById('nav'); //The whole navigation

window.addEventListener('scroll', function(){
  var scroll = window.pageYOffset | document.body.scrollTop;

  if(scroll < 100){
    nav.classList.remove('nav-shrink');
  } else {
    nav.classList.add('nav-shrink');
  }
});
Rhumborl
  • 16,349
  • 4
  • 39
  • 45
Zach4531
  • 33
  • 2
  • Aren't you using some library? This is not standard behavior. If you can show us more of your code, it might help us to help you. Maybe you have some global variables set beforehand. EDIT: It is common to be able to refer to your elements by their ID after all. My bad, didn't know that – Ludovit Mydla Apr 14 '18 at 16:45

1 Answers1

1

This is not specific to ES6. If you have a DOM element with an ID, and use that ID as a variable name (not being declared anywhere else), you'll get the DOM element:

Demo

console.log(hello);
<div id="hello"></div>
blex
  • 24,941
  • 5
  • 39
  • 72
  • I never knew that so thanks for the answer but I'm assuming this is a bad practice and should use getElementById – Zach4531 Apr 14 '18 at 17:34
  • @Zach4531 Yes, I don't think you should use that "feature" in your code. If you share your code with other people, they might find it confusing that the variable is not declared anywhere, and if you work with libraries or other people's code, their code _could_ make yours break. So, do it the clean way :) – blex Apr 14 '18 at 17:39