Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Having trouble with a bit of javascript

Can anyone tell me why this bit of Javascript won't work when I paste it into it's own file and link to it?

(function () {

  // Create mobile element
  var mobile = document.createElement('div');
  mobile.className = 'nav-mobile';
  document.querySelector('.nav').appendChild(mobile);

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

  // toggleClass
  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;
      }
  }

  // Mobile nav function
  var mobileNav = document.querySelector('.nav-mobile');
  var toggle = document.querySelector('.nav-list');
  mobileNav.onclick = function () {
      toggleClass(this, 'nav-mobile-open');
      toggleClass(toggle, 'nav-active');
  };
})();

So I'm basically pasting that into a blank file called main.js then linking to it using:

<script src="main.js" type="text/javascript></script>

1 Answer

<script src="main.js" type="text/javascript"></script>

you're missing an endquote in your type attribute

Sorry that was just a typo. I've gone over everything like that a few times to double check I'm not being stupid.