Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

highlight link javascript

// Get all sections that have an ID defined
const sections = document.querySelectorAll("section[id]");

// Add an event listener listening for scroll
window.addEventListener("scroll", navHighlighter);

function navHighlighter() {
  
  // Get current scroll position
  let scrollY = window.pageYOffset;
  
  // Now we loop through sections to get height, top and ID values for each
  sections.forEach(current => {
    const sectionHeight = current.offsetHeight;
    const sectionTop = current.offsetTop - 50;
    sectionId = current.getAttribute("id");
    
    /*
    - If our current scroll position enters the space where current section on screen is, add .active class to corresponding navigation link, else remove it
    - To know which link needs an active class, we use sectionId variable we are getting while looping through sections as an selector
    */
    if (
      scrollY > sectionTop &&
      scrollY <= sectionTop + sectionHeight
    ){
      document.querySelector(".navigation a[href*=" + sectionId + "]").classList.add("active");
    } else {
      document.querySelector(".navigation a[href*=" + sectionId + "]").classList.remove("active");
    }
  });
}
Comment

PREVIOUS NEXT
Code Example
Javascript :: calculate sum in empty array javascript 
Javascript :: regex pattern to validate phone number in jitterbit 
Javascript :: how to draw vertical dash line in react native 
Javascript :: leaflet core 
Javascript :: get input string js 
Javascript :: find element in array underscore js 
Javascript :: check if specific letter exist in string javascript 
Javascript :: render text in for loop react in function 
Javascript :: install video-react 
Javascript :: how to build with a specific .env file node 
Javascript :: add a string regex in angular input 
Javascript :: react icons cdn 
Javascript :: postDataToFirebase 
Javascript :: $_GET data using javascript 
Javascript :: update password using comparePassword() Method 
Javascript :: How to concatenate two textbox values in JavaScript 
Javascript :: how to categorize a data in an array of object in javascript 
Javascript :: js create and call function 
Javascript :: in in sequelize 
Javascript :: get all data in collection firebase react 
Javascript :: json schema e.g. 
Javascript :: const { something} javascript 
Javascript :: como instalar la nueva version de node-js en ubuntu 
Javascript :: get last element of array javascript 
Javascript :: kaboom.js 
Javascript :: javascript table show only first n rows 
Javascript :: Implementing state lifecycle in react class component 
Javascript :: Hide ReactTooltip after hover off 
Javascript :: python dictionary setdefault in javascript 
Javascript :: cheerio library to parse the meta tags in url 
ADD CONTENT
Topic
Content
Source link
Name
1+3 =