-1

I keep receiving this error for my mobile navigation:

Uncaught TypeError: Cannot set property 'onclick' of null

I cannot find the cause. The error is referring to the last 3/4 lines of code.

var theToggle = document.getElementById('toggle');

function hasClass(elem, className) {
    return new RegExp(' ' + className + ' ').test(' ' + elem.className + ' ');
}

function addClass(elem, className) {
    if (!hasClass(elem, className)) {
        elem.className += ' ' + className;
    }
}

function removeClass(elem, className) {
    var newClass = ' ' + elem.className.replace( /[\t\r\n]/g, ' ') + ' ';
    if (hasClass(elem, className)) {
        while (newClass.indexOf(' ' + className + ' ') >= 0 ) {
            newClass = newClass.replace(' ' + className + ' ', ' ');
        }
        elem.className = newClass.replace(/^\s+|\s+$/g, '');
    }
}

function toggleClass(elem, className) {
    var newClass = ' ' + elem.className.replace( /[\t\r\n]/g, " " ) + ' ';
    if (hasClass(elem, className)) {
        while (newClass.indexOf(" " + className + " ") >= 0 ) {
            newClass = newClass.replace( " " + className + " " , " " );
        }
        elem.className = newClass.replace(/^\s+|\s+$/g, '');
    } else {
        elem.className += ' ' + className;
    }
}

theToggle.onclick = function() {
   toggleClass(this, 'on');
   return false;
}
halfer
  • 19,824
  • 17
  • 99
  • 186
CharlyAnderson
  • 737
  • 2
  • 14
  • 34

3 Answers3

2

Looks like Your .js loaded before DOM was initialized, and document.getElementById('toggle') found nothing, as there is no element with this id yet.

Place this <script> in the end of HTML.

Razzka
  • 641
  • 5
  • 16
1
  1. your DOM is not yet ready when the code has been executed.
  2. or the DOM with id="toggle" does not exists.

if the error scenario is number 1, you can fix it by wrapping you codes in a self invoking function

$(document).ready(function(){ ... }); or (function(){ ... })();

what are the difference between two?

Community
  • 1
  • 1
Jairo Malanay
  • 1,327
  • 9
  • 13
0
theToggle.addEventListener("click", function(){
   toggleClass(this, 'on');
   return false;
});
Vicheanak
  • 6,444
  • 17
  • 64
  • 98
  • 1
    This might be the solution, but please provide information on WHY this is the answer, so people can actually learn. – Randy Aug 05 '16 at 08:48