DEV Community

mutesialine
mutesialine

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

index.html

<html>
<head>
<title>capgemini</title>
</head>
<body>
//navbar
<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>
        </div>
        <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>
        </div>
    </div>
<script src="/navbar.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

index.css

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

.navwhite{
  @apply bg-white text-black; 
}
Enter fullscreen mode Exit fullscreen mode

navbar.js

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.remove('navwhite')
    image2.style.display="none";
    image1.style.display="block"
  }
  else{
    navbar.classList.add('navwhite')
    image1.style.display= "none";
    image2.style.display="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)