PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, October 19, 2022

[FIXED] How to detect the wordpress admin bar in javascript?

 October 19, 2022     admin, detection, javascript, navbar, wordpress     No comments   

Issue

I am using a navbar that hides when scrolling down the pages, and showing up when scrolling up in Wordpress.

The typical problem is that the WP admin bar gets on top of the navbar.

As my navbar srcoll hiding code is made in javascript, I cannot use the css code that I used before to add a space on the top of the navbar when the admin bar is present :

body.admin-bar #navbar-section {
  top: 32px;
}

So I would like to know how I can detect the presence of the WP admin bar in javascript so that I can add the space on top using the following code :

    if adminbar present then
document.getElementById("navbar-section").style.top = "32px";
    else
document.getElementById("navbar-section").style.top = "0px";

Thanks a lot as I have been struggling for a long while now... :} !


Solution

The admin toolbar has an ID of "wpadminbar". So your code just needs to reference this:

const $wpadminbar = document.getElementById('wpadminbar');
const $navbar_section = document.getElementById('navbar-section');
if ($wpadminbar){
     $navbar_section.style.top = "32px";
} else {
     $navbar_section.style.top = "0px";
}

You can also use Node.contains:


const $wpadminbar = document.getElementById('wpadminbar');
const $navbar_section = document.getElementById('navbar-section');
if (document.body.contains($wpadminbar)){
     $navbar_section.style.top = "32px";
} else {
     $navbar_section.style.top = "0px";
}


Answered By - Tokant
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing