Modify anchor link color in a one-page website by using Jquery to detect scroll position changes when reaching different page sections

Each if statement contains specific numbers to change the text color of the visited/current/active anchor link. The height of the page is dependent on its width. How can this be resolved? Apologies if my explanation is confusing, English isn't my strongest language XD

Codepen

var bottomPage = $(window).scrollTop() + $(window).height() == $(document).height();
var scrollPos = $(window).scrollTop();

if(scrollPos >= 300 && scrollPos <= 854){
    $('header nav ul li a').removeClass();
    $('header nav ul li a[href="#about-nav"]').addClass('current');
}else if (scrollPos >= 855 && !bottomPage){
    $('header nav ul li a').removeClass();
    $('header nav ul li a[href="#portfolio-scroll"]').addClass('current');
}else if (bottomPage){
    $('header nav ul li a').removeClass();
    $('header nav ul li a[href="#contact-scroll"]').addClass('current');
}else {
    $('header nav ul li a').removeClass();
}

Answer №1

Finally cracked it!

Behold, my latest masterpiece of code. I have a feeling this one is flawless.

var bottomPage = $(window).scrollTop() + $(window).height() == $(document).height();
var about = $('div#about-nav').position();
var aboutPos = about.top;
var portfolio = $('div#portfolio-scroll').position();
var portfolioPos = portfolio.top;

if(scrollPos >= aboutPos && scrollPos < (portfolioPos - 1)){
$('header nav ul li a').removeClass();
$('header nav ul li a[href="#about-nav"]').addClass('current');
}else if (scrollPos >= (portfolioPos - 1) && !bottomPage){
$('header nav ul li a').removeClass();
$('header nav ul li a[href="#portfolio-scroll"]').addClass('current');
}else if (bottomPage){
$('header nav ul li a').removeClass();
$('header nav ul li a[href="#contact-scroll"]').addClass('current');
}else {
$('header nav ul li a').removeClass();
}

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

Button background must be grayscale, while the text should remain unaffected

I have a variety of buttons with different background images. My goal is to apply a grayscale filter to the backgrounds by default and remove the filter on hover, without affecting the color of the button text. Currently, when I apply the grayscale filter ...

Adding a space after a comma automatically upon saving changes in VSCode

Whenever I input code (t,s) into the system and make changes to it, it automatically transforms into (t, s) with an added space after the comma. Is there a way to avoid VScode from adding this extra space on its own? ...

Does the margin fall within the element's boundaries?

Consider this code: <html> <head> <title>Understanding CSS Box Model</title> </head> <body> <section> <h1>An example of h1 inside a section</h1> </section> </body> </html& ...

Error: JSON parsing error encountered at position x due to unexpected token

While I understand this question has been asked multiple times before, the situation here is unique. I am utilizing getJSON to retrieve data from a Database. The returned result is a valid JSON (validated by various JSON validators), but I am encountering ...

Creating a secondary title for a Bootstrap Navigation Bar

I have a unique Bootstrap 4 website that features a navbar. The navbar consists of a special brand section with an image and title text, followed by the rest of the navbar elements. You can view it here: https://jsfiddle.net/zmbq/aq9Laaew/218793/ Now, I a ...

Adjust the field's color depending on the outcome displayed within

I'm trying to implement a feature where the field value changes to green when "OK" is selected and red when "NOK" is chosen. I have written the following JavaScript code but it's not working as expected - the colors change before clicking submit, ...

Dynamic Data Causes Highcharts Date Formatting to Adapt

I wanted to create a line graph using Highcharts with the Date Format on x-axis set to "%b %e". For example, I expected 06/27/2014 to be displayed as Jun 17. Despite setting the date-format correctly, Highcharts seems to automatically change it when rende ...

What method does Apple use to apply overflow:hidden to elements within position:fixed?

After conducting my own experiments and delving into the topic online, I discovered that elements using position: fixed do not adhere to the overflow: hidden property of their parent element. This also applies to children within the fixed positioned elemen ...

Tracking activities in Laravel app---How to monitor actions

Is there a way to split the date and time onto one line in my script? I'm having trouble achieving this as shown here: Here is my current script: <div class="tab-pane active" id="tab_overview"> <div ...

Executing a PHP function with an onclick event on an `<li>` tag via AJAX: What's the best approach?

Can you assist me in using AJAX to call a PHP function that communicates with an external server when the onclick event is triggered? <div class="container"> <h3 style=color:blue;>DETAILS </h3> <ul class="nav nav-pills" style="backgro ...

Modifying the appearance and behavior of an element dynamically as the page is being loaded using AngularJS

Struggling with a challenge for two days now, I have attempted to implement a panel-box using bootstrap and AngularJS. Within the confines of a controller, my code looks like this: <div id="menu2a"> <div class="panel list-group"> <div ...

What is the best way to limit a plugin to only one version of jQuery when there are 2 versions included on a page?

As I develop a piece of Javascript code to embed into my client's websites, I have concerns about potential conflicts with other versions of jQuery that they may be using. While I have found some guidance in the jQuery documentation, implementing it l ...

"An easy way to dynamically update a select dropdown based on the data of the corresponding row in a table using jQuery

Having some trouble with dynamically populating form input fields in a table. The first row works fine, but when I change the select option in the second row, it affects the previous field instead of the current row: How can I ensure that changing the sel ...

Sequential asynchronous requests with a time delay

let updateData = function() { $.ajax({ . . . }) .done(function() { console.log('Update complete'); setInterval(updateData, 10000); }); } I am trying to update some data every 10 seconds. Ho ...

Web addresses and the presence of secure HTTP protocol?

Can someone confirm if it is true that when using https, URLs should begin with //[your-domain]/? A friend using WordPress mentioned this but I haven't been able to find specific information on the topic. ...

Employing promises for retrieving ajax data

I've been struggling to make sure my code waits for an ajax call to finish before proceeding, as I need data in an array first. No matter what I try, it seems like promises might be the best solution in this scenario. Currently, the ajax call still oc ...

Combining CSS to Align Two Form Fields Side by Side

I recently came across an online form and I'm attempting to customize it by aligning the phone and email text fields next to each other. I have made some progress, but the formatting is not quite right. The fields are too small and adjusting their siz ...

implementing a fixed header in HTML

I am facing a challenge where I have a header with dynamic height and fixed position. My goal is to position the container div right below the header. However, since the header height varies, using a fixed value for margin-top is not feasible. Any sugges ...

Can floated divs be prevented from collapsing without taking up any width?

Let's discuss an issue that is not related to block elements collapsing when their children are floated, and has nothing to do with clearing at all. Imagine having a set of floated divs like: <div class="column">Column 1</div> <div cl ...

Is it possible to combine an id and HTML element with jQuery's find() function?

just curious: when working with CSS, I can target a div using #display div Is there a similar method in jQuery? I am trying to locate the DIV with id="displayFirst" (a page) and then find the div within this DIV with data-role=content. Something like: ...