The links have IDs for scrolling to certain sections, but they are jumping over and missing some of the content

This particular project involves a website that consolidates all its pages/sections into one page. Each section has been assigned a unique ID (such as section1, section2, section3, etc.) and these IDs have also been linked to the top navigation href's, for example

<a href="#section2">About Us</a>
. Upon clicking on "About Us" in the top navigation, you will be directed to the corresponding div with the ID of #section2.

While I've managed to get this part working correctly, I'm encountering a few issues - despite my research efforts, I haven't been able to pinpoint the exact keywords needed to find solutions! Therefore, I haven't found anything useful yet and any assistance would be greatly appreciated.

The problems I'm facing are:

  1. When clicking a button from the menu, it jumps to the specified section but not to the very top of that section - instead, it scrolls down about 100px. Why does this happen?
  2. Is there a way to enable smooth scrolling without the abrupt jump?
  3. How can I easily apply the class .active to buttons when they are clicked and scrolled to their respective sections?

You can find the code snippet here: http://jsfiddle.net/nd8MN/3/, which includes both the HTML and CSS used.

[The rest of the HTML and CSS code snippets follow...]

Answer №1

Indeed, a handy little script can handle this task for you.

$(document).ready(function() {
  function filterPath(string) {
  return string
    .replace(/^\//,'')
    .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
    .replace(/\/$/,'');
  }
  var locationPath = filterPath(location.pathname);
  var scrollElem = scrollableElement('html', 'body');

  $('a[href*=#]').each(function() {
    var thisPath = filterPath(this.pathname) || locationPath;
    if (  locationPath == thisPath
    && (location.hostname == this.hostname || !this.hostname)
    && this.hash.replace(/#/,'') ) {
      var $target = $(this.hash), target = this.hash;
      if (target) {
        var targetOffset = $target.offset().top;
        $(this).click(function(event) {
          event.preventDefault();
          $(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
            location.hash = target;
          });
        });
      }
    }
  });

  // select the first "scrollable" element
  function scrollableElement(els) {
    for (var i = 0, argLength = arguments.length; i <argLength; i++) {
      var el = arguments[i],
          $scrollElement = $(el);
      if ($scrollElement.scrollTop()> 0) {
        return el;
      } else {
        $scrollElement.scrollTop(1);
        var isScrollable = $scrollElement.scrollTop()> 0;
        $scrollElement.scrollTop(0);
        if (isScrollable) {
          return el;
        }
      }
    }
    return [];
  }

});

Just so you know, credit for this script goes to CSS Tricks.

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

Retrieving a single object from an array in node.js utilizing elemMatch

My goal is to extract a single object from an array of objects in a data collection using elemMatch. Here is the sample data: [ { "_id": "5ba10e24e1e9f4062801ddeb", "user": { "_id": "5b9b9097650c3414ac96bacc", "firstName": "blah", ...

Issues encountered when executing unit tests using karma

I encountered these issues in the logs. Seeking advice on how to proceed. Thank you. I've attempted uninstalling and reinstalling phantomjs, clearing out my node modules and bower component directories. Everything was functioning as expected before, a ...

Converting a string into a list extracted from a text document

Within a file, the data (list) is structured as follows: [5,[5,[5,100,-200],200,-400],300,-500] Upon reading this file in an angular application, the contents are converted into a string object like so: "[5,[5,[5,100,-200],200,-400],300,-500]" Is there ...

What is the method for modifying the chosen color using a select option tag instead of a list?

element, I have a Vue component that features images which change color upon clicking a list item associated with that color. <div class="product__machine-info__colors"> <ul> <li v-for="(color, index) in machine.content[0] ...

What is the secret behind Redactor JS's ability to display properly indented code snippets?

If you take a look at the Redactor JS demo and click on the button to show the HTML source code of the displayed content... ...you will notice that the code is properly indented: Most rich text editors or wysiwyg editors typically display code in a singl ...

forever js is interfering with the operation of a different application

I currently have two very similar Node JS projects that I manage by starting and stopping them using Forever JS. Both projects can run simultaneously on different ports but, when I input the following command: forever stop index.js In one project direc ...

Displaying HTML elements conditionally in React depending on boolean values

Developing a component that limits the display of text to the first 40 characters, but can show the full description when a Chevron click event is triggered. The goal is to have the content expand in a similar fashion as it currently does with the Accord ...

Utilize Flexbox and Material UI to position Item at the bottom of the layout

I'm attempting to include Unassigned Text at the bottom of my Container, following the layout shown in this mockup:https://i.sstatic.net/863cl.png Here is the code I currently have. I'm facing difficulty in getting the border between the play bu ...

Utilize Css3 MediaQueries to nudge @Media switch for hyperlinks

My website currently utilizes css3-mediaqueries.js for a mobile-friendly design, which is working well. However, some users are still requesting to view the "web-version" instead. Is there a way to override the current CSS on the homepage, specifically the ...

Obtain asynchronous view model for component

Is it possible to retrieve a view model from the server and incorporate it into my component? I attempted to do so with the following code snippet, but it is not working as expected: function fetchViewModelFromServerAsync(){ setTimeout(function(){ ...

Showcasing a component for a seven-day period with the power of Javascript

Here is my current JavaScript code: var today = new Date(), d = today.getDate(), m = today.getMonth() + 1, y = today.getFullYear(), date = d + '/' + m + '/' + y, specialDate = '22/10/2012'; if (date == specialDate) { documen ...

What would be the counterpart of setLocale in Yup for the zod library?

How can I set default custom error messages for Zod validation? If I want to use i18n for error messages in Yup, I would do the following: import { t } from "i18next"; import * as yup from "yup"; import "./i18next"; yup.setL ...

How can I use JQuery to save values from a for loop?

After working on a grid, I encountered an issue where only the last value was being returned when trying to fetch all values into an object. Unfortunately, I am stuck and unsure of how to resolve this problem. function item_details(){ var gridDataAr ...

I am struggling to showcase the values of character names stored within an array

I am currently developing a Library Express App and utilizing fake data to easily showcase the values on the screen. const PopularBooks = [ { id: 1, title: "Harry Potter", characters: [ { id: 1, name: "Har ...

The onClick event is not functioning properly with React's select and option elements

Looking for a way to get the option value from each region? const region = ['Africa','America','Asia','Europe','Oceania']; <div className="options"> <select> ...

What are the reasons behind lang sass not functioning within the style tag of a .vue file?

Even though I had previously installed sass-loader and node-sass in my project, I encountered an issue when attempting to use <style lang="sass"> in my vue file. The style did not compile as expected, however it worked perfectly without the lang="s ...

Determine the total row count retrieved from a HTML table using Javascript

Currently, I have an HTML table that is being searched using JavaScript. I am looking to determine the number of rows that are remaining after the search and then display that information to the user. As a beginner, I would like some guidance on how to m ...

Why isn't the justify-content property set to center in my CSS code functioning properly?

For a front-end challenge from Frontend Mentor, I attempted to center a card on the screen using justify-content: center, but it doesn't seem to be working as expected. Any suggestions on how to achieve this? @import url('https://fonts.google ...

A guide to displaying a JSON object in a Jade template and iterating through the data

When I pass a JSON string to a jade file for rendering, I am facing an issue where I can only print the entire string and not its individual elements. How can I print specific elements or iterate through the JSON string? app.js: var http = require(&ap ...

Internet Explorer 11 displays a white X instead of the image

While developing a Single Page Application on Angular 1.5, I encountered a frustrating bug in IE11. Instead of rendering my pictures correctly, I see a white X in a black box. Strangely, the browser is receiving a 200 code response for the image request. C ...