Smooth scrolling in JavaScript can lead to unexpected jumps when using scroll-margin-top

I am currently working on implementing smooth scrolling into my website using JavaScript. However, I have run into a problem with CSS property scroll-margin-top causing a sudden jump at the end. The CSS I am using for scroll margins looks like this:

class or div {
  scroll-margin-top: 6rem;/*adjust size as needed*/
}

In addition to the CSS, I also have a JavaScript function set up for smooth scrolling. The issue arises when scrolling to specific sections, there is a noticeable jump right at the end of the scroll.

Below is the snippet of the JavaScript code in question:

    var ssSmoothScroll = function () {
      $('a[href^="#"], area[href^="#"]').on('click', function (e) {
        var target = $($(this).attr('href'));
        if (target.length) {
          e.preventDefault();
          $('html, body').stop().animate({
            scrollTop: target.offset().top
          }, cfg.scrollDuration, 'swing', function () {
            window.location.hash = target.attr('id');
          });
        }
      });
    };  

If you have any suggestions on how to resolve this issue and achieve a seamless smooth scrolling experience without the jarring jump at the end, please let me know.

Here is the JsFiddle demo for reference

Answer №1

calculates the scroll-margin-top value of the specified element and deducts it from the scroll destination.

$(document).ready(function () {
  $('a[href^="#"], area[href^="#"]').on('click', function (e) {
    var target = $($(this).attr('href'));
    if (target.length) {
      e.preventDefault();
      var scrollMargin = target.css('scroll-margin-top'); // Retrieve scroll-margin-top value
      var offset = scrollMargin ? parseInt(scrollMargin) : 0; // Parse the retrieved value
      $('html, body').stop().animate({
        scrollTop: target.offset().top - offset // Consider the scroll-margin-top value
      }, 1000, 'swing', function () {
        window.location.hash = target.attr('id');
      });
    }
  });
});
 body {
      margin: 0;
      padding: 0;
    }
    
    #first,
    #second,
    #third,
    #fourth,
    #fifth {
      scroll-margin-top: 6rem;
    }

    /* Additional styles for demonstration purposes */
    section {
      height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 2rem;
    }
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
 <nav>
    <ul>
      <li><a href="#first">first</a></li>
      <li><a href="#second">second</a></li>
      <li><a href="#third">third</a></li>
      <li><a href="#fourth">fourth</a></li>
      <li><a href="#fifth">fifth</a></li>
    </ul>
  </nav>

  <section id="first">first</section>
  <section id="second">second</section>
  <section id="third">third</section>
  <section id="fourth">fourth</section>
  <section id="fifth">fifth</section>

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

The Flask AJAX request is returning an empty ImmutableMultiDict, whereas the same AJAX request successfully works with http.server

Making the switch from http.server to Flask has caused issues with my image upload functionality using AJAX. This is being done in Python 3. Attempts at troubleshooting that have failed: I have ensured multipart/form-data is included in the Ajax req ...

IE compatibility with CSS2 selectors

Is there a plugin, preferably jQuery, that can enable the use of CSS2 selectors like 'parent > child' and 'element:first-child' in my stylesheet for IE6, which doesn't seem to support them natively? ...

Webpage with visual representation

Currently in the process of redesigning my university's drama department website, I'm looking to incorporate three images side by side with spacing and captions. The captions need to have a header that's styled differently from the caption i ...

Progress Bars Styled with CSS Percentages

I need help creating a basic CSS percentage bar. To get started, visit and paste the following code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://w ...

Is it possible to make the background of the HTML Embed object transparent instead of grey?

I am currently utilizing Firefox along with an open-source plugin for video playback. The video is adjusted to fit the available space as defined by the width and height of the embed object, but occasionally a slight grey border appears on the right or bot ...

Having trouble with CSS Locator identifying an element in your Protractor Test?

In the Protractor test snippet below, I am attempting to calculate the quantity of div elements using the CSS locator: let list = element.all(by.css('div[class="ag-header-cell ag-header-cell-sortable"]')); expect(list.count()).toBe(11); ...

Revolutionize Your App with React Native's Interactive Bottom Sheet Option

Hello there! I am trying to create a FlatList with multiple items, each of which should trigger a bottom-sheet when clicked. I want to make this dynamic but I'm encountering an error. TypeError: undefined is not an object (evaluating `_this[_reactNat ...

Displaying components in Vue 2 using data from an ajax call

How can components retrieved from an ajax response be rendered? For instance, suppose I have registered a component called "Test" and within the ajax response I encounter: <p>dummy paragraph</p> <test></test> <!-- vue component ...

Utilizing CSS grid layouts to ensure images expand to fit the dimensions of the designated column and

I am currently working with a CSS grid layout that is displaying as follows: .image__gallery-grid { max-height: none; grid-template-columns: repeat(4, minmax(0, 1fr)); grid-template-rows: repeat(2, minmax(0, 1fr)); gap: 2.5rem; dis ...

Expanding the jQuery AutoComplete Plugin: A Guide to Implementing the bind keyup Event

Currently, I am utilizing a plugin that enhances the features of the jQuery AutoComplete UI Plugin: https://github.com/experteer/autocompleteTrigger/blob/master/jquery-ui.autocompleteTrigger.js Within the select method, an event and ui variable are passe ...

Error encountered when accessing JSON data from the DBpedia server in JavaScript

Hello everyone and thank you for your help in advance. I have encountered this error: Uncaught SyntaxError: Unexpected identifier on line 65 (the line with the "Var query", which is the third line) and when I click on the Execute button, I get another e ...

Failure to link style sheet to document

Experiencing some difficulties with a seemingly simple task that I can't figure out. When I check my code in the browser, none of my styles are being applied to the HTML elements. The style sheet is located in the same folder as the main document, and ...

Having trouble executing a MongoDB query through Mongoose without using a REST API

Dealing with the Express router has been an uphill battle for me. While Mongoose models work seamlessly within routes, I've hit a roadblock when trying to utilize the models in other files without routes. Whenever I attempt to run the file containing ...

The view in my node is rendering a different ejs view, and I have verified that the path

Currently, I am using the render method for a view in EJS. The path is correct but the view in the route is an old one that I used for testing purposes. This is my server.js code: https://i.sstatic.net/Xl1Ct.png Here is my route: https://i.sstatic.net/ ...

What is the reason I am unable to upload personalized templates using <script> elements?

I have a dilemma where I need to swap out multiple templates from a library with my own custom ones without forking the original templates. When I include the templates in my index.html page like: <script type="text/ng-template" id="first-template"> ...

Learn how to simultaneously play two audio files using the same identifier in JavaScript

I'm facing an issue with two audio files that have a progress bar and both have the same ID: <audio id="player" src="<?=base_url('mp3/'.$rec->file)?>"></audio> </p> ...

Creating a personalized .hasError condition in Angular 4

I am currently in the process of modifying an html form that previously had mandatory fields to now have optional fields. Previously, the validation for these fields used .hasError('required') which would disable the submit button by triggering a ...

Guide to comparing 2 arrays and determining the quantity of identical elements

If an AJAX call returns 2 arrays upon successful execution, the arrays will be different each time but may contain some common elements. For instance: array1 = [x, y, z, a] array2 = [x, y, y, y, x, z, y, z, z] The goal is to determine how many times eac ...

js The correct value is not being set to the div's style.top

function gamestart(){ var gr; var gr = true; console.log(gr==true); if(gr == true){ console.log("we have activated pointer key detection dear Mr.ketsebaot") document.onkeydown = checkk; } } function checkk(e){ cons ...

Struggling to make the text color change when hovering

On my website, I added a tab called newarrival at the top of the page. When you hover over this tab, I want the text to turn blue to indicate that it's a link. However, despite my efforts, it doesn't seem to be working as expected. You can see th ...