DEV Community


Posted on

Eventlistener(scroll) using tailwindcss and vanilla Javacript

Scroll event happen when user scroll in a saturn direction and it works on the browser window lets take an example of the page where navbar change background ,text and image when scroll event happen


<div class="w-full h-[800px]  relative  pb-10 bg-heroImage  bg-cover">
        <div id="navbar" class="navwhite text-white   fixed p-8 top-0 w-full  flex  gap-8 justify-between lg:justify-start z-50 items-center "> 
                <img id="image1"  class="w-28" src="./img/logo-white.svg" alt="logowhite">
                <img  id="image2" class="w-28" src="./img/logoblue.svg" alt="logoblue">

                <div class="flex   gap-3">
                    <a href="">Insights</a>
                    <a href="">Industries</a>
                    <a href="">Services</a>
                    <a href="">Carees</a>
                    <a href="">News</a>
                    <a href="">About us</a>
        <div class="absolute bottom-2 lg:bottom-32 py-6  px-8  space-y-2  bg-opacity-90 text-white   lg:left-20 mx-4 bg-[#056295]  lg:mx-0">
            <h1 class="text-3xl font-bold ">AUTHORS OF CHANGE</h1>
            <p class=" text-lg ">Making the world more inclusive with words</p>
<script src="/navbar.js"></script>
Enter fullscreen mode Exit fullscreen mode


@tailwind base;
@tailwind components;
@tailwind utilities;

  @apply bg-white text-black; 
Enter fullscreen mode Exit fullscreen mode


function changeNav(){
  var navbar= document.getElementById('navbar');
  var image1=document.getElementById('image1');
  var image2 = document.getElementById("image2");
  var scrollyValue=window.scrollY;
  if(scrollyValue < 20){
    navbar.classList.add('navwhite') "none";"block"
  window.addEventListener("scroll", changeNav);

Enter fullscreen mode Exit fullscreen mode

Before:The fixed navbar

Image description

After:when scrolling navbar changes background color, textcolor, and logo image until user stop scrolling

Image description

Top comments (0)