简体   繁体   中英

uncaught TypeError: Cannot read property 'classList' of null

Hi Im trying to make a shrinking header, I almost have it working however i keep getting the above error for this section of the js files

var cbpAnimatedHeader = (function() {

var docElem = document.documentElement,
    header = document.querySelector( '.cbp-af-header' ),
    didScroll = false,
    changeHeaderOn = 300;

function init() {
    window.addEventListener( 'scroll', function( event ) {
        if( !didScroll ) {
            didScroll = true;
            setTimeout( scrollPage, 250 );
        }
    }, false );
}

function scrollPage() {
        var sy = scrollY();
        if ( sy >= changeHeaderOn ) {
            var windowtab = $(window).width();
            if (windowtab >= 1021)
            {
            classie.add( header, 'cbp-af-header-shrink' );
            }
        }
        else {
            classie.remove( header, 'cbp-af-header-shrink' );
        }
        didScroll = false;
}

function scrollY() {
    return window.pageYOffset || docElem.scrollTop;
}

init();
})();

and

var classie = {
// full names
 hasClass: hasClass,
addClass: addClass,
removeClass: removeClass,
toggleClass: toggleClass,
 // short names
has: hasClass,
 add: addClass,
remove: removeClass,
toggle: toggleClass
};

I had it working in DNN when I add a module for the jQuery however when I had it to the skin, I end up with the above console error

This line in the script:

header = document.querySelector('.cbp-af-header')

@ MDN for document.querySelector()

it says that, the first element in the document with the class is returned .


So may be you are looking for .querySelectorAll("selector/s") :

document.querySelectorAll(".cbp-af-header");

@ MDN for document.querySelectorAll()

returns a list of all elements (div in case) supplied within the document.

I encountered the same problem. I realized that IIFE was executed before the DOM was completely loaded. If you are use jQuery, try wrapping it in $(document).ready()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM