How to load a jQuery script last?

How to get this to load last?

 <script type="text/javascript">
  jQuery(document).ready(function(){
   jQuery("div.domTip_tipBody").mouseover(function(){
   jQuery("#yyy a.tippy_link").css("background-color","yellow");});  

   jQuery("div.domTip_tipBody").mouseout(function(){
   jQuery("#yyy a.tippy_link").css("background-color","red");
 }); 
 });  
 </script>

It is running before “div.domTip_tipBody” is being run (which is generated by a shortcode) so nothing happens.

Read More

I have tried:

<script src="script.js" type="text/javascript" defer="defer"></script>

in my header.php before

</head> 

but it doesn’t help.

Have seen “window.onload =” but not sure how to apply it.

Any insight is appreciated.

Thanks

Related posts

Leave a Reply

5 comments

  1. add_action('wp_footer','myscript_in_footer');
    function myscript_in_footer(){
    ?>
    <script type="text/javascript">
      jQuery(document).ready(function(){
       jQuery("div.domTip_tipBody").mouseover(function(){
       jQuery("#yyy a.tippy_link").css("background-color","yellow");});  
    
       jQuery("div.domTip_tipBody").mouseout(function(){
       jQuery("#yyy a.tippy_link").css("background-color","red");
     }); 
     });  
     </script>
    <?php
    }
    
    1. Put the code inside a file named your_name.js.
    2. Add the following to your functions.php file:

      function wpse47618_load_script_last()
      {
          wp_enqueue_script( 'zzz_your_name', get_stylesheet_directory_uri().'your_name.js', array( 'jquery' ), '0', true );
      }
      add_action( 'wp_enqueue_scripts', 'wpse47618_load_script_last', 99999 );
      
    3. Check your pages source code if the script was added successfully and if the path to the file is correct. If you use FireBug or other dev tools, click the filename and see it the script content is there.
    4. You’re done.
  2. This looks like a jQuery event delegation issue. If the new DOM elements are added after the page has loaded, jQuery wont read them. So you need to tell jQuery before hand to bind an event if any such element exists now or in future.

    try $.delegate('div.domTip_tipBody','mouseover', function(e){
    jQuery("#yyy a.tippy_link").css("background-color","yellow");});
    });

    See http://api.jquery.com/delegate/ , http://lab.distilldesign.com/event-delegation/

  3. You can simply add the script to footer.php and it will probably work, but it’s not the best way to avoid jQuery conflicts.

    The best way is to enqueue the script from a separate file. See http://codex.wordpress.org/Function_Reference/wp_enqueue_script which has a parameter to load scripts in footer via wp_footer .

    And see The Developer’s Guide To Conflict-Free JavaScript And CSS In WordPress: http://wp.smashingmagazine.com/2011/10/12/developers-guide-conflict-free-javascript-css-wordpress/