Home > other >  Navbar not changing color on scroll even though other effects on scroll are working
Navbar not changing color on scroll even though other effects on scroll are working

Time:10-30

So, I have this page where navbar/header is included in the hero section. In the hero section the navbar/header is transparent. When it scrolls to different sections, I want it to change background color also the navlinks should change style depending on which section it is on.

The navlink color change works fine however the header/navbar background color change is not working. I have used plain JS for all these effects. But can't figure out why the background color change is not working. What have I got wrong?? Edit: I tried to console.log on my js and got this " main.js:68 Uncaught TypeError: Cannot read properties of undefined (reading 'add') at HTMLDocument.navbarChange"

Could someone please explain?

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta content="width=device-width, initial-scale=1.0" name="viewport" />

    <title>Test</title>
    <meta content="" name="description" />
    <meta content="" name="keywords" />

    <!-- Favicons -->
    <link href="assets/img/log.ico" rel="icon" />
   

    <!-- Google Fonts -->
    <link
      href="https://fonts.googleapis.com/css?family=Open Sans:300,300i,400,400i,600,600i,700,700i|Montserrat:300,300i,400,400i,500,500i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i"
      rel="stylesheet"
    />
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@200;300;400;500;600;700;800;900&family=Merriweather:ital,wght@0,300;0,400;0,700;1,300;1,400;1,700;1,900&display=swap" rel="stylesheet">
    <!-- Vendor CSS Files -->
    <link href="assets/vendor/aos/aos.css" rel="stylesheet" />
    <link
      href="assets/vendor/bootstrap/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <link
      href="assets/vendor/bootstrap-icons/bootstrap-icons.css"
      rel="stylesheet"
    />
    <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet" />
    <link
      href="assets/vendor/glightbox/css/glightbox.min.css"
      rel="stylesheet"
    />
    <link href="assets/vendor/swiper/swiper-bundle.min.css" rel="stylesheet" />

    <!-- Template Main CSS File -->
    <link href="assets/css/style.css" rel="stylesheet" />
  </head>

  <body>

    <!-- ======= Hero Section ======= -->
    <section id="hero">

    <!-- ======= Header ======= -->
    <header id="header" >
      <div >
        <div >
          <a href="index.html"><h1>Test.</h1></a>
        </div>

        <nav id="navbar" >
          <ul>
            <li><a  href="#hero">Home</a></li>
         
            <li><a  href="#services">Services</a></li>
            <li><a  href="#feature">Featured</a></li>
            <li><a  href="#pricing">Pricing</a></li>
            <li><a  href="#faq">FAQ</a></li>
            <li><a  href="#contact">Contact</a></li>
            
            <li><a href="#" ><button type="button" >Log In</button></a></li>
            <li><a href="#" ><button type="button" >Book a Demo</button></a></li>
          </ul>
          <i ></i>
        </nav>
        <!-- .navbar -->
      </div>
    </header>
    <!-- End Header -->

      <div >
       
      </div>
    </section>

    <!-- End Hero -->


             <main>
        <section id="services" >
        </section>
              </main>

              <footer>
              <footer>
            <!-- Vendor JS Files -->
              <script src="assets/vendor/aos/aos.js"></script>
              <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
              <script src="assets/vendor/glightbox/js/glightbox.min.js"></script>
              <script src="assets/vendor/isotope-layout/isotope.pkgd.min.js"></script>
              <script src="assets/vendor/ email-form/validate.js"></script>
              <script src="assets/vendor/swiper/swiper-bundle.min.js"></script>
              <script src="https://cdnjs.cloudflare.com/ajax/libs/typed.js/2.0.11/typed.min.js"
              integrity="sha512-BdHyGtczsUoFcEma MfXc71KJLv/cd sUsUaYYf2mXpfG/PtBjNXsPo78 rxWjscxUYN2Qr2 DbeGGiJx81ifg=="
              crossorigin="anonymous"></script>

              <!-- Template Main JS File -->
              <script src="assets/js/main.js"></script>
  </body>
  </html>
  

style.css

#header {
  height: 90px;
  transition: all 0.5s;
  z-index: 997;
  transition: all 0.5s;
  background: transparent;
  box-shadow: 0 4px 10px -3px rgba(191, 191, 191, 0.5);
}

#header .colorful {
  background: linear-gradient(
    305deg,
    #d8eae5,
    #e0ece9,
    #f9e9a7,
    #f4f6fb,
    #fdebe9,
    #fff
  );
  background-size: 1000% 1000%;

  -webkit-animation: live-gradient 17s ease infinite;
  -moz-animation: live-gradient 17s ease infinite;
  animation: live-gradient 17s ease infinite;
  position: relative;
}

main.js

(function() {
  "use strict";

  /**
   * Easy selector helper function
   */
  const select = (el, all = false) => {
    el = el.trim()
    if (all) {
      return [...document.querySelectorAll(el)]
    } else {
      return document.querySelector(el)
    }
  }

  /**
   * Easy event listener function
   */
  const on = (type, el, listener, all = false) => {
    let selectEl = select(el, all)
    if (selectEl) {
      if (all) {
        selectEl.forEach(e => e.addEventListener(type, listener))
      } else {
        selectEl.addEventListener(type, listener)
      }
    }
  }

  /**
   * Easy on scroll event listener 
   */
  const onscroll = (el, listener) => {
    el.addEventListener('scroll', listener)
  }

  /**
   * Navbar links active state on scroll
   */
  let navbarlinks = select('#navbar .scrollto', true)
  const navbarlinksActive = () => {
    let position = window.scrollY   200
    navbarlinks.forEach(navbarlink => {
      if (!navbarlink.hash) return
      let section = select(navbarlink.hash)
      if (!section) return
      if (position >= section.offsetTop && position <= (section.offsetTop   section.offsetHeight)) {
        navbarlink.classList.add('active')
      } else {
        navbarlink.classList.remove('active')
      }
    })
  }

/**
   * Navbar color change after first section
   */

  window.addEventListener('load', navbarlinksActive)
  onscroll(document, navbarlinksActive)


  let header = select('#header',true)
  const navbarChange = () => {
    let position = window.scrollY
    if(position > window.innerHeight){
      header.classList.add('colorful')
    }else{
      header.classList.remove('colorful')
    }
  }
  window.addEventListener('load', navbarChange)
  onscroll(document, navbarChange)

  /**
   * Scrolls to an element with header offset
   */
  const scrollto = (el) => {
    let header = select('#header')
    let offset = header.offsetHeight

    if (!header.classList.contains('header-scrolled')) {
      offset -= 16
    }

    let elementPos = select(el).offsetTop
    window.scrollTo({
      top: elementPos - offset,
      behavior: 'smooth'
    })
  }

  /**
   * Back to top button
   */
  let backtotop = select('.back-to-top')
  if (backtotop) {
    const toggleBacktotop = () => {
      if (window.scrollY > 100) {
        backtotop.classList.add('active')
      } else {
        backtotop.classList.remove('active')
      }
    }
    window.addEventListener('load', toggleBacktotop)
    onscroll(document, toggleBacktotop)
  }

  /**
   * Mobile nav toggle
   */
  on('click', '.mobile-nav-toggle', function(e) {
    select('#navbar').classList.toggle('navbar-mobile')
    this.classList.toggle('bi-list')
    this.classList.toggle('bi-x')
  })

  /**
   * Mobile nav dropdowns activate
   */
  on('click', '.navbar .dropdown > a', function(e) {
    if (select('#navbar').classList.contains('navbar-mobile')) {
      e.preventDefault()
      this.nextElementSibling.classList.toggle('dropdown-active')
    }
  }, true)

  /**
   * Scroll with ofset on links with a class name .scrollto
   */
  on('click', '.scrollto', function(e) {
    if (select(this.hash)) {
      e.preventDefault()

      let navbar = select('#navbar')
      if (navbar.classList.contains('navbar-mobile')) {
        navbar.classList.remove('navbar-mobile')
        let navbarToggle = select('.mobile-nav-toggle')
        navbarToggle.classList.toggle('bi-list')
        navbarToggle.classList.toggle('bi-x')
      }
      scrollto(this.hash)
    }
  }, true)

  /**
   * Scroll with ofset on page load with hash links in the url
   */
  window.addEventListener('load', () => {
    if (window.location.hash) {
      if (select(window.location.hash)) {
        scrollto(window.location.hash)
      }
    }
  });
  /**
   * Animation on scroll
   */
  window.addEventListener('load', () => {
    AOS.init({
      duration: 1000,
      easing: 'ease-in-out',
      once: true,
      mirror: false
    })
  });

})()

CodePudding user response:

I solved my issue with jquery as follows:

<script>
      let myNav = $("#header");
      let height = $("#hero").height();

        $(window).on('scroll', function() {
          "use strict";
          if ($(window).scrollTop() >= height) {
            myNav.addClass("colorful");
          } else {
            myNav.removeClass("colorful");
          }
        });
    </script>

CodePudding user response:

Edit the following class style -

#header.colorful {
  background: linear-gradient(
    305deg,
    #d8eae5,
    #e0ece9,
    #f9e9a7,
    #f4f6fb,
    #fdebe9,
    #fff
  );
  background-size: 1000% 1000%;

  -webkit-animation: live-gradient 17s ease infinite;
  -moz-animation: live-gradient 17s ease infinite;
  animation: live-gradient 17s ease infinite;
  position: relative;
}
  • Related