Document ready function - Not loading the code first

1k Views Asked by At

I have a function that works on the body onload="" but I need it to load before other elements of the page and I'm trying to add the document ready function in the header but it just doesn't seem to work.

f1menu() {
    $('.menuH').hover(
        function() {
            $('.menuC').stop().animate({width: '90px'},333)
        }, 
        function() {
            $('.menuC').stop().animate({width: '-0'}, 333)
        }
    );
}

$(document).ready(function() {
    f1menu();
});

So the onload function that works is just this one below:

onload="$('.menuH').hover(function() {$('.menuC').stop().animate({width: '90px'}, 333)}, function() {$('.menuC').stop().animate({width: '-0'}, 333)});"
2

There are 2 best solutions below

11
Scott Marcus On BEST ANSWER

Note that the following answer was provided before the OP changed the question.

You should write:

  function f1menu(){}

not,

  f1menu(){}

In addition, you can streamline your document.ready code by simply passing the function that you want called when the document is ready, directly to jQuery:

$(function() {
     $('.menuH').hover(
         function() {
            $('.menuC').stop().animate({width: '90px'}, 333);
         }, 
         function() {
            $('.menuC').stop().animate({width: '-0'}, 333);
         }
     );
});

UPDATE:

After OP revised the question, the solution (not a recommended approach by the way) would be to just insert the script into the body of the page, but AFTER any elements that the function references, such as:

 <body>

     <!-- elements that the code references must come before the code -->
     <script>
        // .menuH and .menuC elements must have already been loaded into DOM
        $('.menuH').hover(
           function() {
               $('.menuC').stop().animate({width: '90px'},333)
           }, 
           function() {
               $('.menuC').stop().animate({width: '-0'}, 333)
           }
        );
     </script>

     <!-- Rest of HTML -->
 </body>
0
DCruz22 On

It doesnt know f1menu is a function since you didnt declare it as one. Try this:

function f1menu(){ //logic
}