Home > front end >  check if class exists on that page javascript
check if class exists on that page javascript

Time:10-29

I have an index page and a dashboard, on the index I'm using typewriter and particlesjs on the index only, and on the dashboard I have a sidebar.

If I have all the code as-is, I get errors as the page is still looking for typewriter and particlesjs on all pages.

So I have attempted to wrap each section around an if so the plan is if that class or id exists on that page it will only render that JS. So I've created the following code.

edited code below based on groovy_guy's answer

document.querySelector('nav .toggle').addEventListener('click', e => {
  document.querySelector('nav .hidden').classList.toggle('show')
});

let checkTypewriter = document.getElementById('typewriter');
if (checkTypewriter.length > 0) {
  new Typewriter('#typewriter', {
    strings: ['Website Developer', 'Freelancer' , 'System Admin'],
    autoStart: true,
    loop: true
  });
}

let checkParticlesjs = document.getElementsByClassName('particlesjs');
if (checkParticlesjs.length > 0) {
  let particles = Particles.init({
    selector: '.particlesjs',
    color: ['#48F2E3', '#48F2E3', '#48F2E3'],
    connectParticles: true,
    maxParticles: 200
  });
}

let checkSidebar = document.getElementsByClassName('sidebar');
if (checkSidebar.length > 0) {
  user_wants_collapse = false;

  // Fetch all the details element.
  const details = document.querySelectorAll("details");

  // Add the onclick listeners.
  details.forEach((targetDetail) => {
    targetDetail.addEventListener("click", () => {
      // Close all the details that are not targetDetail.
      details.forEach((detail) => {
        if (detail !== targetDetail) {
          detail.removeAttribute("open");
        };
      });
    });
  });

  document.querySelector('section').addEventListener('click', (ev) => {
    // close any open details elements that this click is outside of
    let target = ev.target;
    let detailsClickedWithin = null;

    while (target && target.tagName != 'DETAILS') {
      target = target.parentNode;
    };

    if (target && target.tagName == 'DETAILS') {
      detailsClickedWithin = target;
    };

    Array.from(document.getElementsByTagName('details')).filter(
      (details) => details.open && details != detailsClickedWithin
    ).forEach(details => details.open = false);

    // if the sidebar collapse is true and is re-expanded by clicking a menu item then clicking on the body should re-close it
    if (user_wants_collapse == true && (document.querySelectorAll('.sidebar details'))) {
      document.querySelector('body').classList.add('is--expand');
    };
  });

  // when the sidebar menu is clicked this sets the user_wants_collapse var to true or false and toggles is--expand class on body
  document.querySelector('.sidebar .menu-link').addEventListener('click', () => {
    document.querySelector('body').classList.toggle('is--expand');
    user_wants_collapse = !user_wants_collapse

    document.querySelector('.sidebar').classList.toggle('is--expand');

    // show all text
    document.querySelectorAll('.sidebar .title').forEach((el) => {
      el.classList.toggle('hidden');
    });

    // changing sidebar menu items and menu collapse icons
    const icon = document.querySelector('.menu-link-arrows span');

    if (icon.classList.contains('fa-angle-double-left')) {
      icon.classList.remove('fa-angle-double-left');
      icon.classList.add('fa-angle-double-right');
    } else {
      icon.classList.remove('fa-angle-double-right');
      icon.classList.add('fa-angle-double-left');
    }
  });

  // making sure the sidebar menu items re-expands the sidebar on click
  let x = document.querySelectorAll('.sidebar details');
  let i;

  for (i = 1; i < x.length; i  ) {
    x[i].addEventListener('click', () => {
      // changing sidebar menu items and menu collapse icons
      // change menu items and menu collapse icons
      const icon = document.querySelector('.sidebar-drop-parent-arrow span');

      if (icon.classList.contains('fa-chevron-down')) {
        icon.classList.remove('fa-chevron-down');
        icon.classList.add('fa-chevron-up');
      } else {
        icon.classList.remove('fa-chevron-up');
        icon.classList.add('fa-chevron-down');
      }

      if (document.querySelector('body').classList.contains('is--expand')) {
        document.querySelector('body').classList.remove('is--expand');
      };
    });
  };
};

when loading the JS I'm not getting any console errors but I'm not seeing any result of the JS.

CodePudding user response:

Why don't you use querySelector()? I think that's more uniform across your codebase. Besides, I see that you only care about one element and not a list of elements, so this method is ideal since it gets the first element that encounters.

const checkTypewriter = document.querySelector('#typewriter')
if (checkTypewriter) {
  // Element with an ID 'typewriter' exist in the DOM.
}

const checkParticlesjs = document.querySelector('.particlesjs')
if (checkParticlesjs) {
  // Element with a class named "particlesjs" exist in the DOM.
}

Also, make sure to check if an element exist before attaching an event listener:

const toggleNav = document.querySelector('nav .toggle')

if (toggleNav) {
  toggleNav.addEventListener('click', (e) => {
    document.querySelector('nav .hidden').classList.toggle('show')
  });
}

CodePudding user response:

For Javascript:

var checkTypewriter = document.getElementsByClassName('typewriter');
    if (checkTypewriter.length > 0) {
        // Here write your code
    }

var checkParticlesjs = document.getElementsByClassName('particlesjs');
    if (checkParticlesjs.length > 0) {
        // Here write your specific code
    }

For JQuery:

    if ($("#typewriter")[0]){
        // Here write your code
    } 

    if ($(".particlesjs")[0]){
        // Here write your specific code
    } 

This is how you can check if your classes exist,

  • Related