2

I am trying to animate open (+) and close (x) buttons for main navigation. It's not working properly and I am getting this error.

Uncaught TypeError: Cannot read property 'addEventListener' of null

JavaScript

document.querySelector( "#nav-toggle" ).addEventListener( "click", function() {
  this.classList.toggle( "active" );
});

HTML

<a id="nav-toggle"   href="#navi" data-toggle="collapse" 
 data-target="#bs-example-navbar-collapse-1">
    <span></span>
</a>
Eric TMD
  • 33
  • 1
  • 6
  • 2
    document.querySelector( "#nav-toggle" ) would be null, meaning it's not finding any elements. Is it running after the document has loaded? – helion3 May 29 '15 at 00:08
  • Could you provide some code as to how this is all loaded? Nothing wrong with your listener, it's just not finding the element. – Shan Robertson May 29 '15 at 00:14
  • 1
    Have you read Felix Kling's question "[Why does jQuery or a DOM method such as `getElementById()` not find the element?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element)" – David says reinstate Monica May 29 '15 at 00:14

1 Answers1

0

Your code should work. It could be an issue of when the javascript runs or a conflict with your data library. The library for collapse might be overwriting your id. Try to use a page inspector like firebug to find out if the id changes after load.

Below is your code toggling the link to red.

document.querySelector( "#nav-toggle" ).addEventListener( "click", function() {
  this.classList.toggle( "active" );
});
.active {color:red}
<a id="nav-toggle"   href="#navi" data-toggle="collapse" 
 data-target="#bs-example-navbar-collapse-1">
    <span>test</span>
</a>
wolfhammer
  • 2,491
  • 1
  • 9
  • 11