Admin Bar menu item that executes Javascript but does not reload the page?

If you return false in that Javascript function the click will not be propagated and the page will also not reload.

Even better, you can specify a onclick attribute for a menu item. So you definition would become this:

function my_admin_bar_class_switch( &$wp_admin_bar ) {
    // $wp_admin_bar is passed by reference, you don't need the global var
    $wp_admin_bar->add_menu( 
        array( 
             'parent'   => 'theme_options'
            ,'title'    => __( 'showdebug', AHF_LANG )
            ,'href'     => '' // This can stay empty
            ,'meta'     => array(
                'onclick' => 'jQuery(".wrap").toggleClass("showdebug"); return false;'
            )
        ) 
    );
}
add_action( 'admin_bar_menu', 'my_admin_bar_class_switch', 70 );

In that case you don’t need to hook up the onclick event yourself. I see two other possible errors there: wp_head is an action, not a filter, so by returning the script it won’t be printed. Also, you depend on showdebug being part of the id, but because you don’t specify the ID it is generated from the title. If that string is translated this ID won’t stay the same.

Leave a Comment