Why does jquery code only work at the end of my html-body section?

I have the following code for creating tabs. It works at the end of the html body section, but not if I put it at the beginning - before all divs are defined. Why could this be?

<script type="text/javascript"> $("ul.tabs li.label").hide(); $("#tab-set > div").hide(); $("#tab-set > div").eq(0).show(); $("ul.tabs a").click( function() { $("ul.tabs a.selected").removeClass('selected'); $("#tab-set > div").hide(); $(""+$(this).attr("href")).show(); $(this).addClass('selected'); return false; } ); $("#toggle-label").click( function() { $(".tabs li.label").toggle(); return false; }); </script> 
+4
source share
3 answers

you need to wrap it with a finished document block. this prevents code from running until the page is fully loaded.

 <script type="text/javascript"> $(function() { // do something on document ready $("ul.tabs li.label").hide(); $("#tab-set > div").hide(); $("#tab-set > div").eq(0).show(); $("ul.tabs a").click( function() { $("ul.tabs a.selected").removeClass('selected'); $("#tab-set > div").hide(); $(""+$(this).attr("href")).show(); $(this).addClass('selected'); return false; } ); $("#toggle-label").click( function() { $(".tabs li.label").toggle(); return false; }); }); </script> 
+5
source

Most likely, because the DOM is not ready yet, and therefore they do not exist.

So you need to do the following:

 $(function() { // Any code in here will only be executed when the DOM is ready. }); 
+10
source
 jQuery(function($) { // put your code in here and it will be executed // when the document has fully loaded. }); 
0
source

All Articles