Hide WP-Admin Bar Button, Temporarily Hide JS

Sometimes checking fixed headers or footers or sticky headers or popups ..etc we need t ohide the admin bar temporarly. This works great on those cases.

This can be added to any button…

document.addEventListener('DOMContentLoaded', function() {
  const hideButton = document.querySelector('#wp-admin-bar-hide-admin-bar');
  
  if (hideButton) {
    hideButton.addEventListener('click', function() {
      const adminBar = document.querySelector('#wpadminbar');
      const html = document.documentElement;
      
      if (adminBar) {
        // Check current state and toggle
        if (adminBar.style.display === 'none') {
          // Show/Toggle again if you want to add the button somewhere else to toggle it :)
          adminBar.style.display = '';
          html.style.setProperty('margin-top', '32px', 'important');
          html.style.setProperty('--wp-admin--admin-bar--height', '32px');
        } else {
          // Hide on Clicked hideButton
          adminBar.style.display = 'none';
          html.style.setProperty('margin-top', '0px', 'important');
          html.style.setProperty('--wp-admin--admin-bar--height', '0px');
        }
      }
    });
  }
});

…but I like to add button to the admin bar itself like this

add this to the functions.php to add the button to the admin bar

add_action( 'admin_bar_menu', function( $wp_admin_bar ) {
    $wp_admin_bar->add_node( array(
        'id'     => 'hide-admin-bar',
        'title'  => '<span style="font-family: dashicons" class="dashicons dashicons-arrow-up-alt2"></span> ',
        'href'   => '#',
        'parent' => 'top-secondary',
			'meta'   => array(
				'class' => 'hide-admin-bar',
			),
    ) );
}, 999 );

If this solution saved you time and money consider supporting