Adding with javascript to admin bar. Works in Chrome/Safari, not Firefox

I’m trying to add a new menu item to the WordPress admin bar. The sub menu item contains a select drop down to switch themes. In Firefox with href => false it generated <a href=""> and when I clicked the select it reloaded the page. I changed it to <a href="#">. That fixed the page reload when clicking on the select… but the javascript isn’t working.

The code itself works just fine in Chrome and Safari on Mac. I haven’t tested IE or any browsers on Windows yet. In Firefox on Mac it does nothing.

Here’s the code generated by the plugin:

<li id="wp-admin-bar-switch_themes" class="menupop">
    <a href="#"><span>Switch Themes</span></a>
    <ul>
            <li id="wp-admin-bar-abstractambienceantisocialapertureapzauldbackstagebig-easybiznizzbloggingstreamboastbold-newsbusy-beecaffeinatedcanvascanvas-buddypress-betachapterscinchcity-guidecodacoffee-breakcontinuumcrispcush" class="">
                    <a href="#">
                            <select name="themeswitcher" onchange="location.href=this.options[this.selectedIndex].value;" style="color: #000; text-shadow: none;">
                                    <option value="http://themes.fusionized.com?wptheme=Abstract" style="color: #000; text-shadow: none;">Abstract</option>
                                    <option value="http://themes.fusionized.com?wptheme=Ambience" style="color: #000; text-shadow: none;">Ambience</option>
                            </select>
                    </a>
            </li>
    </ul>
</li>

Nothing fancy in the code to generate the admin bar items…

$wp_admin_bar->add_menu( array( 'id' => 'switch_themes', 'title' => __( 'Switch Themes', 'textdomain' ), 'href' => '#' ) );
$wp_admin_bar->add_menu( array( 'parent' => 'switch_themes', 'title' => $theme_switcher->theme_switcher_markup('dropdown'), 'href' => '#' ) );

3 Answers
3

Obviously you cannot put a select tag inside a A anchor. What happens is related to event bubbling: Firefox takes the A anchor click into account, not the select control.

Change your html to:

 <li id="wp-admin-bar-abstractambienceantisocialapertureapzauldbackstagebig-easybiznizzbloggingstreamboastbold-newsbusy-beecaffeinatedcanvascanvas-buddypress-betachapterscinchcity-guidecodacoffee-breakcontinuumcrispcush" class="">

                            <select name="themeswitcher" onchange="location.href=this.options[this.selectedIndex].value;" style="color: #000; text-shadow: none;">
                                    <option value="http://themes.fusionized.com?wptheme=Abstract" style="color: #000; text-shadow: none;">Abstract</option>
                                    <option value="http://themes.fusionized.com?wptheme=Ambience" style="color: #000; text-shadow: none;">Ambience</option>
                            </select>

            </li>

and it should work cross-platform.

Leave a Comment