Problem with a dynamic section on a single-page site

I'm currently working on building my very first single-page website.

If you want to check out the jsfiddle for it, here's the link: http://jsfiddle.net/dgfhjxLt/

The main issue I'm facing is related to the first div section. When a user scrolls through the pages, the link colors should change to indicate which page they're on. This functionality works smoothly for all links except the first one.

Whenever users land on the site initially, the first link should show as active with blue text. However, this only takes effect after scrolling a bit, and then it works as intended.

I've been stuck trying to fix this problem for about an hour now. Surely, there must be a simple solution?

Sharing the jQuery code snippet below:

jQuery(document).ready(function($) {   
var offsetHeader = 60;

$('.scroll').click(function(){
    var $target = $($(this).attr('href'));
    $(this).parent().addClass('active');
    $('body').stop().scrollTo( $target , 800, {'axis':'y', offset: -offsetHeader});
    return false;
});

/**
     * This part handles the highlighting functionality.
     * We use the scroll functionality again, some array creation and 
     * manipulation, class adding and class removing, and conditional testing
     */
    var aChildren = $("nav li").children(); // find the a children of the list items
    var aArray = []; // create the empty aArray
    for (var i=0; i < aChildren.length; i++) {    
        var aChild = aChildren[i];
        var ahref = $(aChild).attr('href');
        aArray.push(ahref);
    } // this for loop fills the aArray with attribute href values

    $(window).scroll(function(){
        var windowPos = $(window).scrollTop(); // get the offset of the window from the top of page
        var windowHeight = $(window).height(); // get the height of the window
        var docHeight = $(document).height();

        for (var i=0; i < aArray.length; i++) {
            var theID = aArray[i];
            var divPos = $(theID).offset().top-60; // get the offset of the div from the top of page
            var divHeight = $(theID).height(); // get the height of the div in question
            if (windowPos >= divPos && windowPos < (divPos + divHeight)) {
                $("a[href='" + theID + "']").addClass("active");
            } else {
                $("a[href='" + theID + "']").removeClass("active");
            }
        }

        if(windowPos + windowHeight == docHeight) {
            if (!$("nav li:last-child a").hasClass("nav-active")) {
                var navActiveCurrent = $(".nav-active").attr("href");
                $("a[href='" + navActiveCurrent + "']").removeClass("nav-active");
                $("nav li:last-child a").addClass("nav-active");
            }
        }
    });
});

Answer №1

Your JavaScript library is using the active class on an anchor, but you have mistakenly applied the active class to the li tag in the first element. To correct this, simply move the active class to the anchor tag like so:

<li><a class="scroll active" href="#test1">test1</a></li>

DEMO

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

Enable images to overlap with pre-set dimensions

Is it achievable for an image to overlap another div (a bootstrap column) while maintaining a fixed size of 155px? I am utilizing bootstrap columns (col-9 and col-3). This is the desired outcome (for illustration purposes, Orange and Grey boxes are image ...

JQuery relative element

I am on a quest to find the nearest element that includes a specific class....this is all in an effort to uncover the "cousin" of my current element.... my attempt using the following failed: $('myelement').closest('*:has(.class1)').fi ...

Center the p tag vertically

To ensure the text inside the p tag aligns vertically in the middle, I've set a specific height for the tag. While this works perfectly for single-line text, it shifts to the top of the p tag when there are two lines of text. It's important to k ...

Utilize the ::before pseudo-element exclusively for the initial node

Here is the text I need to generate : https://i.sstatic.net/HzKP9.png This represents my HTML code : <!DOCTYPE html> <head> <meta charset="utf-8"/> <link rel="stylesheet" href="style5.css"> <title& ...

Firefox does not support responsive tables, while Chrome does

Firstly, let's take a look at this Fiddle by resizing in Firefox and Chrome. I also attempted to troubleshoot the issue mentioned here: Why do Firefox and Opera ignore max-width inside of display: table-cell?, but unfortunately had no success. table ...

Is there a way for me to determine which .js script is modifying a particular HTML element?

Let's take a look at a specific website as an example: This particular website calculates value using a .js script embedded in the HTML itself. Upon inspecting the source code by pressing F12, we can locate the element containing the calculated valu ...

Changing the Row's Background Color in Angular When the Button is Clicked

My code includes a list where each row has a button to open a sidebar. Due to the large number of elements in the list, I want the background color of the row to turn yellow when the button is clicked, as a way to indicate what has been selected. Currently ...

Enhance your SVG with a stylish border by adding a decorative

Is there a way to add a blue or black border that follows the curve of an SVG used as a divider? <svg width="100%" height="96px" viewBox="0 0 100 100" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" prese ...

What is the best way to adjust the sizes of two images within the same class to your liking?

My class called cbImage has a fixed CSS for all images. .cbImage img { width: 100%; height: 100%; } However, I don't want all images to have the same width and height. Is there a way to change the width and height of different images as need ...

Determine the width of a div by utilizing SASS and following a series of incremental steps

Let's discuss the current scenario: I have a parent div that consists of multiple child elements which vary in number. (2, 3, 4) The goal is to determine the appropriate width for each step element dynamically: For 2 steps: 50% For 3 steps: 33.3% ...

Require assistance resolving a CSS problem on IE8?

Greetings everyone, I am currently facing some compatibility issues with my style sheets, particularly in IE 8. The CSS code below functions perfectly in my Chrome/Firefox style sheet, but unfortunately, it does not have any effect on my IE stylesheet. # ...

Tips for choosing a nested element within a div using CSS

I'm looking to target a specific child element within a div using CSS. Here's the HTML code I have: <div class='body'> <text>This is a text element</text> </div> Instead of adding a class or an ID, I want to ...

Modify the color of the text input by the user in an AJAX-enhanced text box

After successfully implementing an autocomplete textbox using AJAX Autocomplete, I decided to enhance the feature with some Fuzzy logic. Now, as the user enters 3 characters, my database returns a list of records that match those characters. The search re ...

IE8 - Unable to use rgba()

I'm currently facing an issue with RGBA() manipulation in jQuery while using IE 8. Here's the code I have so far: $('.set').click(function (e) { var hiddenSection = $('div.hidden'); hiddenSection.fadeIn() . ...

php not writing on initial attempt

I have been storing some data in local storage variables and I want to transfer them to a file created using PHP. On my HTML page, there is a function named updatesurvey. This function performs the following tasks: var newDate = new Date(); var ...

The Nivo slider's position is being adjusted

I've been trying to adjust the width of the Nivo slider on my blog. Right now, it's taking up the entire width of the page wrapper and I want to add some space on the left and right sides so that it's centered and lines up with the navigatio ...

Utilize Bootstrap cards to display images across the full width of the page

I am using the Bootstrap card component https://getbootstrap.com/docs/4.0/components/card/ to display an image. The issue I'm facing is that on the Bootstrap template, it adds a margin around the image. I would like the image to take up the full width ...

Is it possible to use jQuery to create a fade in effect on an AJAX

My current setup involves a form that uses AJAX and PHP to insert data into my database. AJAX function insertBill() { $.post('insert_bill.php', $('#insertbill').serialize(), function(data) { $('#bills'). ...

I could really use some assistance in designing a website with a grid layout

I'm envisioning a unique layout: Any suggestions? I'm struggling to translate my vision into code. Bootstrap has crossed my mind, but there's an issue with elements spanning across columns and rows in the 6x4 grid I've set up for the ...

Here is a unique rewrite: "Utilize jQuery to extract all data-id and amount from an HTML page, then send it through an

Is there a way to retrieve the data-id and amount values from this HTML page using jQuery? Once I have gathered that information, I would like to store it in an array and then submit it via an AJAX call. It's important to note that this is a Laravel p ...