How to make jQuery work in admin area?

I have included Twitter Bootstrap with in my theme options page in WordPress to help style the theme options page. Before, when I was de-registering jQuery and adding my own version, all code was working with the $, because I didn’t have to worry about WordPress’s way of always having a jQuery appended to everything, I could just use $ and be done with it.

Unfortunately, you are not supposed to de-register jQuery, even if it’s only done on your own admin pages.

Read More

So I looked around for some ways to still use the $ in jQuery and wrote this:

(function($){   
    $(document).ready(function(){
        $('.posts').click(function(){
            if ($(this).attr("id") == "list"){
                $('.sectionLists').show();
            } else {
                $('.sectionLists').hide();
            }
        });
});
})(jQuery);

There are no console errors – in my code, yet none of my Twitter Bootstrap Javascript dependent functions are working, such as Popovers, Tabs or anything else of that nature, and the above code doesn’t even work.

However if I paste it into Chrome console and hit enter, it works as it should.

Whats going on?

Related posts

Leave a Reply

2 comments

  1. You are probably trying to call jQuery before it is loaded – that’s why it doesn’t work in page but does in the console.

    Are you adding the jQuery dependency like below and as shown in the Codex at wp_enqueue_script?

    function iamb_inc_bootstrap() {
    
        wp_register_script(
            'js_bootstrap',
            get_template_directory_uri() . '/bootstrap/js/bootstrap.min.js',
            array('jquery'),
            '20130219',
            true
        );
    
        wp_enqueue_script('js_bootstrap');
    }
    add_action('wp_enqueue_scripts', 'iamb_inc_bootstrap');
    
  2. Disregarding the correct way of enqueueing scripts and stylesheets, this is how I always do it:

    add_action( 'admin_footer', 'wpse_46677_change_menu_item' );
    
    function wpse_46677_change_menu_item()
    {
        ?>
            <script type="text/javascript">
                jQuery(document).ready( function($) {
                    $( "#menu-appearance" )
                        .find( "li:contains( 'Header' )" )
                        .html( '<a href="themes.php?page=custom-header">My Text</a> ');
                });     
            </script>
        <?php
    }
    

    From this WordPress Answer.