2

I am new to coding. I am receiving this error: "Missing "Use strict" statement" in my Javascript code. Here is my code:

$(function(){
    $('.nav-toggle').on('click',function(){

        $('.main-nav').toggleClass('open');
    });
});

I do not know where to put 'use-strict';. Where do I put the statement?

5
  • This is optional, it shouldn't cause an error.
    – Barmar
    Commented Jan 14, 2016 at 22:56
  • 2
    See stackoverflow.com/questions/1335851/…
    – Barmar
    Commented Jan 14, 2016 at 22:57
  • You don't need the leading $.
    – Mathemats
    Commented Jan 14, 2016 at 22:57
  • @Mathemats Yes he does, that's how you run the code in the jQuery document.ready handler.
    – Barmar
    Commented Jan 14, 2016 at 22:58
  • That's not a JavaScript error, but linter error. Commented Jan 16, 2016 at 7:30

2 Answers 2

3

As Barmar said, the use strict is optional, but if you had to place it somewhere the best place I would say you should put it is

$(function(){
    "use strict";
    $('.nav-toggle').on('click',function(){

        $('.main-nav').toggleClass('open');
    });
});

This is where you have to put it whether you use Jquery or Javascript

4
  • Oops I forgot to put a semi colon make sure your "use strict"; is like this instead of what I wrote
    – JKer
    Commented Jan 14, 2016 at 23:00
  • 2
    Sorry for spelling your name wrong @Barmar I am not wearing my glasses right now its a bit blurry for me
    – JKer
    Commented Jan 14, 2016 at 23:01
  • 1
    You can just edit your own answer to fix anything you want to fix. I added the semi-colon for you.
    – jfriend00
    Commented Jan 14, 2016 at 23:03
  • Ok Thanks, I make too many spelling and syntax mistakes without my glasses I didnt even see the edit button
    – JKer
    Commented Jan 15, 2016 at 0:21
0

(function($){
    "use strict";
    $('.nav-toggle').on('click',function(){

        $('.main-nav').toggleClass('open');
    });
})(jQuery);
.open{
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div>
  <button class="nav-toggle">Open</button>
  <div class="main-nav">
    <ul>
      <li>Home</li>
      <li>Contact</li>
    </ul>
  </div>
</div>

Assuming you want to achieve a responsive navbar effect I have added the relevant code to make this easier.

In the jQuery part, I'm creating an anonymous function and passing it the $ sign so you can use it safely without polluting the global scope. "use strict" use is not mandatory but if you want to use place it inside the anonymous function as I did.

2
  • 3
    How does this solve the problem that the original question asked about?
    – jfriend00
    Commented Jan 15, 2016 at 0:30
  • Yes I am making a responsive nav menu :)
    – Jyan
    Commented Jan 17, 2016 at 22:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.