Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does some jquery code only work if it's 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 place it at the beginning - before all of the divs are defined. Why might that 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>
like image 370
ipso facto Avatar asked Dec 08 '22 07:12

ipso facto


1 Answers

It is most likely because the DOM is not ready yet, and therefore they don't exist.

Therefore you need to do the following:

$(function() {
    // Any code in here will only be executed when the DOM is ready.
});
like image 190
Thomas Avatar answered Jan 12 '23 00:01

Thomas