JavaScript error on admin pages without Meta Box dashboard elements

Support General JavaScript error on admin pages without Meta Box dashboard elements

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #48716
    Nicholas CoxNicholas Cox
    Participant

    When I navigate to any WordPress admin page that's not the Meta Box dashboard (like my custom plugin pages), I get this JavaScript error in the browser console:

    Uncaught TypeError: can't access property "addEventListener", document.querySelector(...) is null

    Apply to dashboard.js

    Where it happens:
    The error occurs in dashboard.js around lines 243-244 where the code tries to add event listeners to .mb-dashboard__news-icon and .mb-dashboard__news__close elements.

    Steps to reproduce:
    1. Go to any admin page that's not the Meta Box dashboard (like Posts, Pages, or a custom plugin page)
    2. Open browser developer tools (F12)
    3. Check the Console tab - you'll see the error

    The problem:
    The dashboard JavaScript is being loaded on all admin pages, but it's trying to attach event listeners to elements that only exist on the Meta Box dashboard page itself. When those elements don't exist, document.querySelector() returns null, causing the error.

    My temporary fix:
    I added null checks before adding the event listeners:

    const newsIcon = document.querySelector( '.mb-dashboard__news-icon' );
    const newsClose = document.querySelector( '.mb-dashboard__news__close' );
    
    if ( newsIcon ) {
        newsIcon.addEventListener( 'click', () => news.classList.toggle( 'mb-dashboard__news--active' ) );
    }
    
    if ( newsClose ) {
        newsClose.addEventListener( 'click', () => news.classList.remove( 'mb-dashboard__news--active' ) );
    }

    Apply to dashboard.js
    WordPress 6.x
    Meta Box (latest version)
    Various admin pages

    thanks

    Nick

    #48727
    Anh TranAnh Tran
    Keymaster

    Hi Nick,

    We only enqueue dashboard.js on the Dashboard page, as you can see the source code here. We run the enqueue styles and scripts on load-$page_hook, which fires only on that admin page.

    Is there any special set up on your site? Can you please try with a fresh install?

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.