cihangir ND cihangir ND - 3 months ago 10
jQuery Question

Jquery does not work if I place it just before </body>, but works if i put it in <head>

I am trying hard for 2 days for this jquery to work in my spring mvc project. (at .jsp files) Finally It worked when I put script tags below head. Is it normal?

I tried everything:
-linking script from ajax google apis.
-linking it from maven dependency.
-linking it from folder.

this does not work:

<html>
<head>
<title>Home</title>

</head>
<body>

<a href="#" id="button">click me</a>

<div id="show_hide" style="display: none;">
hey
</div>

<script type="text/javascript">
$(document).ready(function(){

$('#button').click(function() {
$('#show_hide').show();

});
});
</script>

<script src="webjars/jquery/1.9.1/jquery.min.js"></script>
</body>
</html>


and this works:

<html>
<head>
<title>Home</title>
<script src="webjars/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>

<a href="#" id="button">click me</a>

<div id="show_hide" style="display: none;">
hey
</div>

<script type="text/javascript">
$(document).ready(function(){

$('#button').click(function() {
$('#show_hide').show();

});
});
</script>


</body>
</html>

Answer

You have to write your script after including jQuery.

Like this:

<html>
  <head>
   <title>Home</title>
  </head>
  <body>                
    <a href="#" id="button">click me</a>    
    <div id="show_hide" style="display: none;">
      hey
    </div> 
    <script src="webjars/jquery/1.9.1/jquery.min.js"></script>
    <script  type="text/javascript">
      $(document).ready(function(){
          $('#button').click(function() {
          $('#show_hide').show();   
        });     
      });
    </script>
  </body>
</html>
Comments