"Cannot read property classList" null "when using classList.add

I have this error, but since I am not familiar with the code. This came from a theme in startbootstrap (Creative). File

classie.js

code:

/*!
 * classie - class helper functions
 * from bonzo https://github.com/ded/bonzo
 * 
 * classie.has( elem, 'my-class' ) -> true/false
 * classie.add( elem, 'my-new-class' )
 * classie.remove( elem, 'my-unwanted-class' )
 * classie.toggle( elem, 'my-class' )
 */

/*jshint browser: true, strict: true, undef: true */
/*global define: false */

( function( window ) {

'use strict';

// class helper functions from bonzo https://github.com/ded/bonzo

function classReg( className ) {
  return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
}

// classList support for class management
// altho to be fair, the api sucks because it won't accept multiple classes at once
var hasClass, addClass, removeClass;

if ( 'classList' in document.documentElement ) {
  hasClass = function( elem, c ) {
    return elem.classList.contains( c );
  };
  addClass = function( elem, c ) {
    elem.classList.add( c );
  };
  removeClass = function( elem, c ) {
    elem.classList.remove( c );
  };
}
else {
  hasClass = function( elem, c ) {
    return classReg( c ).test( elem.className );
  };
  addClass = function( elem, c ) {
    if ( !hasClass( elem, c ) ) {
      elem.className = elem.className + ' ' + c;
    }
  };
  removeClass = function( elem, c ) {
    elem.className = elem.className.replace( classReg( c ), ' ' );
  };
}

function toggleClass( elem, c ) {
  var fn = hasClass( elem, c ) ? removeClass : addClass;
  fn( elem, c );
}

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

// transport
if ( typeof define === 'function' && define.amd ) {
  // AMD
  define( classie );
} else {
  // browser global
  window.classie = classie;
}

})( window );

      

the error is in:

elem.classList.add (c);

I am not familiar with the written code. I am including this file along with other js files. And it seems like another js file needs a classie variable .

Editorial staff:

HERE IS AN ERROR IN THE CONSOLE:

Uncaught TypeError: Cannot read property 'classList' of null
  addClass @ classie.js?nngrmm:33
  scrollPage @ cbpAnimatedHeader.js?nngrmm:30

      

ALSO, I have a bug in bootstrap.js.

Uncaught TypeError: $(...).find(...).once is not a function
  Drupal.behaviors.bootstrap.attach @ bootstrap.js?nngrmm:16
  (anonymous function) @ drupal.js?nngrmm:76
  x.extend.each @ jquery.min.js?v=1.10.2:4
  Drupal.attachBehaviors @ drupal.js?nngrmm:74
  (anonymous function) @ drupal.js?nngrmm:412
  x.Callbacks.c @ jquery.min.js?v=1.10.2:4
  x.Callbacks.p.fireWith @ jquery.min.js?v=1.10.2:4
  x.extend.ready @ jquery.min.js?v=1.10.2:4
  q @ jquery.min.js?v=1.10.2:4

      

Somewhere here:

/**
 * @file
 * bootstrap.js
 *
 * Provides general enhancements and fixes to Bootstrap JS files.
 */

var Drupal = Drupal || {};

(function($, Drupal){
  "use strict";

  Drupal.behaviors.bootstrap = {
    attach: function(context) {
      // Provide some Bootstrap tab/Drupal integration.
      $(context).find('.tabbable').once('bootstrap-tabs', function () {
        var $wrapper = $(this);
        var $tabs = $wrapper.find('.nav-tabs');
        var $content = $wrapper.find('.tab-content');
        var borderRadius = parseInt($content.css('borderBottomRightRadius'), 10);
        var bootstrapTabResize = function() {
          if ($wrapper.hasClass('tabs-left') || $wrapper.hasClass('tabs-right')) {
            $content.css('min-height', $tabs.outerHeight());
          }
        };
        // Add min-height on content for left and right tabs.
        bootstrapTabResize();
        // Detect tab switch.
        if ($wrapper.hasClass('tabs-left') || $wrapper.hasClass('tabs-right')) {
          $tabs.on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
            bootstrapTabResize();
            if ($wrapper.hasClass('tabs-left')) {
              if ($(e.target).parent().is(':first-child')) {
                $content.css('borderTopLeftRadius', '0');
              }
              else {
                $content.css('borderTopLeftRadius', borderRadius + 'px');
              }
            }
            else {
              if ($(e.target).parent().is(':first-child')) {
                $content.css('borderTopRightRadius', '0');
              }
              else {
                $content.css('borderTopRightRadius', borderRadius + 'px');
              }
            }
          });
        }
      });
    }
  };

      

Mistake:

$ (context) .find ('. tabbable'). once ('bootstrap-tabs', function () {

Help is needed. Thank.

+3


source to share


3 answers


I ran into the same question today but on a different topic and wanted to post my solution to help others in the future.

The problem is with the cbpAnimatedHeader.js file. This file defines the "scrollPage" function that calls the "classie" function. This is why you initially see that the error is related to the classie.js file. The scrollPage function uses the "header" variable:

if ( sy >= changeHeaderOn ) {
        classie.add(header, 'navbar-shrink' );
    }
    else {
        classie.remove(header, 'navbar-shrink' );
    }

      



However, the title is not defined in such a way that the scrollPage function can read it. To fix the error, you can define the title globally or inside the scrollPage function. I decided to just copy the variable definition into the function. Here's the end result in cbpAnimatedHeader.js :

function scrollPage() {
    var sy = scrollY(),
    header = document.querySelector( '.navbar-fixed-top' );
    if ( sy >= changeHeaderOn ) {
        classie.add(header, 'navbar-shrink' );
    }
    else {
        classie.remove(header, 'navbar-shrink' );
    }
    didScroll = false;
}

      

+11


source


I figured out that my problem was that I moved the cbpAnimatedHeader.js file from the bottom of the body to the head. This caused the title to be empty because the html hadn't been rendered yet.

Instead of adding the title search to the scrollPage function, I wrapped it all up in a jQuery document.



$(function(){
  var cbpAnimatedHeader = (function() {

      var docElem = document.documentElement,
          header = document.querySelector( '.navbar-fixed-top' ),
          didScroll = false,
          changeHeaderOn = 300;

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

      function scrollPage() {
          var sy = scrollY();
          header = document.querySelector( '.navbar-fixed-top' );
          if ( sy >= changeHeaderOn ) {
              classie.add( header, 'navbar-shrink' );
          }
          else {
              classie.remove( header, 'navbar-shrink' );
          }
          didScroll = false;
      }

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

      init();

  })();
});

      

+4


source


Adding my solution here as I was getting the same error but it had nothing to do with the actual Classie plugin.

I used a script here to shrink the top menu on my site in scrolling: http://callmenick.com/post/animated-resizing-header-on-scroll .

I have added additional elements to the page that need a class .smaller

added to them as they will move up and shrink as they scroll to get to the smaller menu. I also added responsive elements that were not always listed on this page. That was the problem, I tried to use the addClass function in Classie on some sensing elements that didn't actually exist when scrolling, so every time the page was scrolled, it would throw several such errors.

So, I have implemented a validation to make sure the react elements exist before trying to add a class to them .smaller

.

From:

window.addEventListener('scroll', function(e){  
    var header = document.querySelector("header");
    var responsive_element = document.querySelector(".responsive_element"); // responsive, not always on the page

    var distanceY = window.pageYOffset || document.documentElement.scrollTop,
        shrinkOn = 160;

    if (distanceY > shrinkOn) {

        classie.addClass(header,"smaller");
        classie.addClass(responsive_element,"smaller");

    } else {

        if (classie.has(header,"smaller")) {

            classie.removeClass(header,"smaller");
            classie.removeClass(responsive_element,"smaller");

        }

    }

});

      

To:

window.addEventListener('scroll', function(e){

    var responsive = false; // to find out if we have those missing elements on the page
    var header = document.querySelector("header"); // always exists

    var distanceY = window.pageYOffset || document.documentElement.scrollTop,
        shrinkOn = 160;

    if (document.querySelector(".responsive_element") != null) {    
    responsive = true; // if we are in mobile mode
    }

    // only deal with the mobile element if it exists
    if (responsive) {
    var responsive_element = document.querySelector(".responsive_element");
    } 


    if (distanceY > shrinkOn) {

        classie.addClass(header,"smaller");

        // only add the smaller class if the element exists
        if (responsive) {
        classie.addClass(responsive_element,"smaller");
        }


    } else {

        if (classie.has(header,"smaller")) {

            classie.removeClass(header,"smaller");

            // only remove the smaller class if the element exists
            if (responsive) {
            classie.removeClass(responsive_element,"smaller");
            }

        }

    }

});

      

0


source







All Articles