JavaScript tip: Improve the way you highlight the current navigation page while scrolling by finding alternative methods to using "scrollY > x"

Currently, my webpage layout is divided into 4 sections - HOME, ABOUT, SKILLS, and CONTACT.

Below is the JavaScript code I am using to highlight a specific section on the navigation bar based on the scroll position:

let home = document.querySelector(".btn1")
let about = document.querySelector(".btn2")
let skills = document.querySelector(".btn3")
let contact = document.querySelector(".btn4")

function highlight(){
  if(window.scrollY > 1)
  {
    home.classList.add("highlight")
  }

  if(window.scrollY > 550)
  {
    home.classList.remove("highlight")
    about.classList.add("highlight")
  }
  else{
    about.classList.remove("highlight")
  }

  if(window.scrollY > 1210)
  {
    skills.classList.add("highlight")
    about.classList.remove("highlight")
  }
  else{
    skills.classList.remove("highlight")
  }

  if(window.scrollY > 2050)
  {
    contact.classList.add("highlight")
    skills.classList.remove("highlight")
  }
  else{
    contact.classList.remove("highlight")
  }
}

window.addEventListener("scroll", highlight);

Although this code works well on my 24" monitor, it becomes less accurate on larger screens like a 27". Are there any better ways to target each page section with scroll?

Answer №1

Create a script that specifies the required elements for the state update using the .offsetTop method.

The pixel value will now adjust dynamically based on changes in the viewport size.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Identify the credit card as either American Express or American Express Corporate

My JavaScript code can successfully detect credit card types, but I have encountered an issue. I am unable to differentiate between American Express and American Express Corporate cards. Is there a way to distinguish them or is it impossible to identify wh ...

Sorting through an array of objects based on a key and value that match another object

Is it possible to filter or query an array with the following structure? [ { 'xml:id': 'Name1', sex: { '$t': 'M' }, occupation: { n: 1 ...

Tips for utilizing the getJson method to pass a variable to a PHP file

I need help with my JavaScript code, as I am trying to pass a datastring containing the value "no" to data.php using getJson in order to receive JSON as a response. However, my JavaScript code is not functioning correctly. Below is the code that I have: J ...

Troubleshooting the Angular Fullstack + CORS issue: "XMLHttpRequest cannot load

I've been wracking my brain trying to figure this out. Utilizing the yeoman generator angular-fullstack, I created a simple Angular app on a NodeJS server with Express. The app makes remote service calls, so there are no API server side calls within ...

A guide on creating a Utility function that retrieves all elements in an array starting from the third element

I've been working on a tool to extract elements from an array starting after the first 2 elements. Although I attempted it this way, I keep getting undefined as the result. // ARRAYS var arr = ['one', 'two', 'three', &a ...

The end of the /if in the small template system fails to correctly detect the desired condition

If I write the following line on its own, he cuts it without any reason. So...: Greetings, I'm in need of assistance regarding an issue that is currently beyond my understanding. I'm facing a challenge with a small TPL-System which requires so ...

Utilizing client-side properties in an onClick event within Next.js framework

class homeNotLoggedIn extends React.Component { componentDidMount() { function logout(){ localStorage.clear() location.reload() } } render() { return ( <div> < ...

Maintaining awareness of which accordion drawer is currently open within a React application

Just getting started with coding, I recently created a collapsible accordion in a NextJs app using the react-collapse package. Everything seems to be working fine, but I'm running into an issue with keeping track of which 'drawer' is current ...

Vue.js numerical input module

My approach involves utilizing Numeral.js: Vue.filter('formatNumber', function (value) { return numeral(value).format('0,0.[000]') }) Vue.component('input-number', { templa ...

Use a text link to upload a file instead of using an input field

While I've seen some discussions on this topic already, the conflicting answers have left me uncertain. Is there a foolproof method for triggering file upload without using an input field? Essentially, I'd like to create a div with an icon and te ...

What could be causing my post request to function properly in POSTMAN but not in my React application?

Here are my POSTMAN headers along with the settings I used to send my POST. It only started working when I switched the Content-Type to application/json. https://i.stack.imgur.com/Xz2As.png https://i.stack.imgur.com/aJtbD.png This pertains to the server ...

Refresh the page with user input after a button is clicked without reloading the entire page, using Python Flask

My python/flask web page accepts user input and returns it back to the user without reloading the page. Instead of using a POST request, I have implemented Ajax/JavaScript to handle user input, process it through flask in python, and display the result to ...

Remove the "x" character from the phone field if an extension is not provided in the Jquery masked input plugin

Currently utilizing the jquery Masked input plugin. The mask I have applied to a field is as follows: "?999-999-9999 x9999" Why is there a ? at the beginning? This was implemented to prevent the field from clearing out when an incomplete number is ente ...

When a single object is entered, JSON returns 'undefined', however, it works successfully when using the .map() function

Utilizing Axios to fetch data from DeezerAPI, I initially rendered information using .map() and everything worked smoothly when passing it to a Component. However, when attempting to access a single JSON object, I encountered an 'undefined' error ...

Tips for arranging various information into a unified column within an Antd Table

Is there a way to display multiple data elements in a single cell of an Ant Design table, as it currently only allows insertion of one data element? I am attempting to combine both the 'transactionType' and 'sourceNo' into a single cell ...

Show the current time using Moment.js

I am currently working on developing a clock component that displays the current time in real-time. Issue: The initial time is correctly displayed when the page loads (HH:mm A), but the clock does not update dynamically. clock.component.ts : import { ...

Display a list of records retrieved from a Firebase query using ngFor to iterate through each instance

I'm currently using firebase and angular to work on a billing list project. The list contains data showing information for a specific month, you can refer to the imagehttps://i.stack.imgur.com/ZR4BE.png While querying the list was smooth, I encounte ...

Creating an SVG element that adjusts to the size of its parent container: tips and tricks

I'm attempting to achieve the following: Displaying an SVG square (with a 1:1 aspect ratio) inside a div element. When the width of the div is greater than its height, the square should adjust to fit within the container based on the height (red box ...

Error encountered on login page: The protocol 'http' does not exist (related to HTML, TypeScript, Angular2, and JavaScript)

Screenshot of the issue: Access the complete project here: Link to a Plunker example of a log-in screen: http://plnkr.co/edit/j69yu9cSIQRL2GJZFCd1?p=preview (The username and password for this example are both set as "test") Snippet with the error in ...

Storing extensive JSON data with AJAX, jQuery, and Java

Currently, I am utilizing jQuery AJAX to call a server-side method and sending a JSON string to the controller. Everything works smoothly when the JSON size is small, but as soon as it exceeds 7kb, the server side rejects the JSON string. I suspect that t ...