Manipulating WP Admin Bar Styles with Events

I’ve mixed feelings about the WordPress admin bar, but that has to do with how third-party solutions add their options to it (plus, it can be disabled if you’re not a big fan of it).

Recently, I published a small plugin – meant primarily for developers – that allows users to toggle admin notices whenever they are working with WordPress (ideally in their local environment, though it can be installed anywhere WordPress is installed).

WP Admin Bar Styles: Toggling with Events

The plugin is simple:

  • It introduces an item into the WP admin bar,
  • When you click on an item, it will toggle any notices or messages that are displayed,
  • When you click on it again, it will toggle their visibility.

But there’s a small nuance that I think is worth covering and that has to do with manipulating the WP admin bar styles using client-side code.

All of this is covered in the initial post, but one aspect of the code that I think is worth sharing for those working with the admin bar and those working with JavaScript.

WP Admin Bar Styles

If you take a look at the source code of the JavaScript that’s included with the plugin, you’ll see the following:

Generally speaking, whenever a user clicks on an item in the WP Admin Bar, it will redirect them to another [server] page or will display a submenu item that does the same. In the case of this plugin, though, it works on the client-side, so it’s all JavaScript.

WP Admin Bar

This means that we have to be aware of the events that are bound to the item so we can manipulate them. And that’s the point I’m getting at in this post.

In short:

Menu items have a blur event attached to them that allow us to trigger so that we can manipulate the WP admin bar styles.

Granted, this doesn’t have to be isolated to client-side functionality, but if you want to manipulate the styles of the menu item when hovering the mouse over the item before loading another page, this is the event you want to use (at least at the time of writing this post).

If you’re working on a plugin that integrates with the menu bar and you want to manipulate WP admin bar styles with JavaScript, the blur event is the one you want to use whenever your particular menu bar item triggers the event.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.