31

I wanted to check my JavaScript with JSLint. I am also using jQuery and JSLint seems to be very unhappy about jQuery.

So, if I have this code:

$(document).ready{
    $("a").click(function() {
        // foo
    });
});

I am getting a few JSLint messages:

Error:

Problem at line 1 character 1: '$' was used before it was defined.

$(document).ready{

...

I had a look at the options but I couldn't figure out how to tell JSLint that this is ok.

If I had only one jQuery call in my code I could just ignore the JSLint message but in 2,500 lines of script there are lots of calls, I can't find the errors I'd like to fix between all these messages.

So, does anyone know how to configure JSLint such that it works with jQuery calls? Or is there something else I can use to check the quality of my JavaScript/jQuery code?

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
newtogit
  • 553
  • 1
  • 8
  • 11

3 Answers3

41

That's not valid JavaScript, it should be:

$(document).ready(function() {

So JSLint will (appropriately) complain about your syntax.

If you want to get rid of the Implied global: $, document message, go to the bottom where it has Predefined (, separated), and put jQuery, $ in that textbox then run again. For the document piece, check Assume a browser in the first column.

All JSLint settings will stick, so you don't have to do this each time you go back.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 2
    To avoid warnings you can add in your code: /*node browser: true */ /*global $ */ – lapo Dec 06 '11 at 11:24
  • jslint is not accepting the implied globals, the only way to get jslint to stop complaining is by putting /*jslint browse: true, continue : true, devel : true, indent : 4, maxerr : 50, newcap : true, nomen : true, plusplus : true, regexp : true, sloppy : true, vars : true, white : true *//*global jQuery: false, $: false */ at the top of the file. Not sure if it is chrome on mac which is acting funny today, but when I enter jQuery and $ in the area for globals, it doesn't work? – pixel 67 Sep 29 '12 at 19:59
21

Add this at the top of your document to get it to validate:

/*jslint browser: true*/ /*global  $*/
Andy Balaam
  • 6,423
  • 6
  • 34
  • 37
  • 1
    Thanks for focusing on the actual question. I had the same one, with proper syntax and this nailed it. – Ken Ingram Dec 16 '16 at 02:26
  • Even in 2018 I have been quickly looking around for this and found it here. It happens to answer the question assuming good code. – Yann Poiré Jun 24 '18 at 09:20
0

Nick is correct about your syntax. The latest release of jQuery (1.4.3) passes JSLint tests. See this blog post: http://blog.jquery.com/2010/10/16/jQuery-143-released/

Vincent
  • 169
  • 1
  • 6