-5

I place my js files inside head tag.

So I do something like this:

<html>
<head>
<script>
    $(function() { //need this to work. Why?
        $(".nc").click(function(){
            alert("ok");
         });
     });
</script>
</head>
<body>
<span class="nc">click</span>
</body>
</html>

My question is, people say it is wrong to use $(function() { but it does not work if I remove this. What should I do?

http://jsfiddle.net/v2hrb4kg/

RGS
  • 4,062
  • 4
  • 31
  • 67
  • http://stackoverflow.com/questions/9899372/pure-javascript-equivalent-to-jquerys-ready-how-to-call-a-function-when-the – Yuriy Yakym Oct 19 '15 at 20:45
  • 1
    Why is that use wrong? `$(function(){});` is just a shortcut for `$(document).ready(function(){});`. – kosmos Oct 19 '15 at 20:46
  • Or just move your javascript code at the end of your page.... – Hackerman Oct 19 '15 at 20:48
  • Maybe they mean that it's wrong to use jquery? Perfectness is in purity :) – Yuriy Yakym Oct 19 '15 at 20:49
  • @Hackerman so in head I must use $(function() ? – RGS Oct 19 '15 at 20:49
  • 1
    @RickJoe how can it be wrong, in the last question I gave you the link to `ready` documentation which shows your shortcut as totally valid and explains why you use it – charlietfl Oct 19 '15 at 20:57
  • @charlietfl in fact, someone comments it was 100% wrong, but I read it wrong. 12h working in front of a computer... sorry for your time! – RGS Oct 19 '15 at 21:03

3 Answers3

1

To answer the question: "why my jquery not work without $(function() { in head?"

It won't work because $(function(){ is a shortcut for $(document).ready(){ which basically says "once all of my HTML is fully loaded, then run this script". without the $(function(){, your script tries to run as soon as it's loaded. Since it's in the head of the document, it tries to run before your element with class="nc" exists. It cannot attach an event handler to an element that doesn't yet exist. So wrapping it in $(function(){ allows it to work even if it's in the head of the document as long as your script appears after the script tag that loads jquery.

That being said it's considered best practice to move as much javascript loading to the bottom of your page to improve loading times, especially scripts that you don't intend to run until the DOM is loaded anyway.

Gregg Duncan
  • 2,635
  • 1
  • 14
  • 20
0
$(function(){ ... });

Is not wrong. It's a JQuery shortcut. You need it, and you should put your JS in a script tag.

Cruiser
  • 1,618
  • 2
  • 16
  • 20
0

It works both ways, that what you mean is a jQuery shortcut, but you can also use this:

$( document ).ready(function() {
  // some code
});

You forgot to use <script> tag, but it is common that you put your JS in the end of <body>.

Mario Kurzweil
  • 490
  • 6
  • 11