The smooth scrolling function in jQuery is producing unexpected outcomes

I'm trying to implement smooth scrolling on my website.

However, the scrollbar is not working as expected. It seems like the smooth scrolling and default jumping to anchor links are happening at the same time.

Here is my HTML code for the Bootstrap navigation:

<nav class="navbar fixed-top navbar-expand-sm navbar-light bg-light mb-3" id="main-nav">
      <div class="container">
        <a class="navbar-brand" href="#">Navbar</a>
        <ul class="navbar-nav">
          <li class="nav-item">
            <a class="nav-link" href="#welcome">Welcome</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#about">About</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#services">Services</a>
          </li>
        </ul>
      </div>
    </nav>

This is the JavaScript code I am using:

<script>
    $('body').scrollspy({ 
      target: '#main-nav',
      offset: $('#main-nav').outerHeight()
    });

    // add smooth scrolling
    $('#main-nav a').on('click',(event) => {
      const sender = event.target; // sender 
      // check for a hash value
      if (sender.hash)
      {
        // prevent default behaviour
        event.preventDefault();

        // get sendar hash
        const hash = sender.hash;
        const navHeight = $('#main-nav').outerHeight();

        // animate smooth scroll
        $('html').animate({
          scrollTop: $(hash).offset().top - (navHeight + 1),
        },1500,() => {
          // add hash to URL after scroll
          this.location.hash = hash;
        });
      }
    });
  </script>

And here is the content of the page:

<section id="welcome">
    <h3>Welcome</h3>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dicta eaque similique cupiditate! Pariatur, aliquid quae recusandae quidem atque cumque perspiciatis possimus quod repudiandae, labore nobis eius voluptatum! Impedit, sint in.
    </p>
</section>
<section id="about">
    <h3>About</h3>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dicta eaque similique cupiditate! Pariatur, aliquid quae recusandae quidem atque cumque perspiciatis possimus quod repudiandae, labore nobis eius voluptatum! Impedit, sint in.
    </p>
</section>
<section id="services">
    <h3>Services</h3>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dicta eaque similique cupiditate! Pariatur, aliquid quae recusandae quidem atque cumque perspiciatis possimus quod repudiandae, labore nobis eius voluptatum! Impedit, sint in.
    </p>
</section>

When I click a link in the navigation bar for the first time, it scrolls over the content header making it disappear.

https://i.sstatic.net/axyhK.png

However, when I click the same link again, it scrolls up a little bit and displays the expected result.

https://i.sstatic.net/DZs1I.png

Does anyone know how to fix this issue and make the scrolling work correctly on the first click? Thank you.

Answer №1

Make the following changes to your code: add padding-top:52px; to the section element and remove - (navHeight + 1) from $(hash).offset().top.

$('body').scrollspy({ 
      target: '#main-nav',
      offset: $('#main-nav').outerHeight()
    });

    // implement smooth scrolling
    $('#main-nav a').on('click',(event) => {
      const sender = event.target; // sender 
      // check for a hash value
      if (sender.hash)
      {
        // prevent default behavior
        event.preventDefault();

        // get sender hash
        const hash = sender.hash;
        const navHeight = $('#main-nav').outerHeight();

        // animate smooth scroll
        $('html').animate({
          scrollTop: $(hash).offset().top,
        },1500,() => {
          // add hash to URL after scroll
          this.location.hash = hash;
        });
      }
    });
section{
  min-height:500px;
  padding-top:52px;
}
#main-nav{
  position:fixed;
  width:100%;
  top:0px;
  background:#ffffff;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<nav class="navbar fixed-top navbar-expand-sm navbar-light bg-light mb-3" id="main-nav">
      <div class="container">
        <a class="navbar-brand" href="#">Navbar</a>
        <ul class="navbar-nav">
          <li class="nav-item">
            <a class="nav-link" href="#welcome">Welcome</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#about">About</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#services">Services</a>
          </li>
        </ul>
      </div>
    </nav>
    
    <section id="welcome">
    <h3>Welcome</h3>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dicta eaque similique cupiditate! Pariatur, aliquid quae recusandae quidem atque cumque perspiciatis possimus quod repudiandae, labore nobis eius voluptatum! Impedit, sint in.
    </p>
</section>
<section id="about">
    <h3>About</h3>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dicta eaque similique cupiditate! Pariatur, aliquid quae recusandae quidem atque cumque perspiciatis possimus quod repudiandae, labore nobis eius voluptatum! Impedit, sint in.
    </p>
</section>
<section id="services">
    <h3>Services</h3>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dicta eaque similique cupiditate! Pariatur, aliquid quae recusandae quidem atque cumque perspiciatis possimus quod repudiandae, labore nobis eius voluptatum! Impedit, sint in.
    </p>
</section>

Answer №2

https://codepen.io/Vikaspatel/pen/jKDRXW

Take a look at this link, it may provide some assistance...

function slideDiv(){
$('ul li a').on('click', function(e){
e.preventDefault();
$('ul li a').removeClass('active');
$(this).addClass('active');
var attrvalue = $(this.getAttribute('href'));
$('html,body').stop().animate({
scrollTop: attrvalue.offset().top
}, 1000)
});
}

Answer №3

If you want to create a smooth and easy scrollspy effect, you can utilize the following code:

<ul class="navigation clearfix">
    <li class=" "><a class="js-scroll-trigger nav-link" href="#home">Home</a></li>
    <li><a class="js-scroll-trigger nav-link" href="#about">About Us</a></li>
    <li><a class="js-scroll-trigger nav-link" href="#amenities">Amenities</a></li>
    <li><a class="js-scroll-trigger nav-link" href="#plan">Floor Plan</a></li>
    <li><a class="js-scroll-trigger nav-link" href="#location">Location</a></li>
    <li><a class="js-scroll-trigger nav-link" href="#contact">Contact Us</a></li>
</ul>


<script src="http://gsgd.co.uk/sandbox/jquery/easing/jquery.easing.1.3.js"></script>
<script> (function ($) 
    { "use strict"; 
        $('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function () 
        { 
            $('a.js-scroll-trigger').removeClass('active') 
            $(this).addClass('active'); 
            if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) 
            { 
                var target = $(this.hash); 
                target = target.length ? target : $('[name=' + this.hash.slice(1) + ']'); 
                if (target.length) 
                { 
                    $('html, body').animate({ scrollTop: (target.offset().top - 72) }, 1000, "easeInOutExpo"); 
                    return false; 
                } 
            } 
        }); 
    })(jQuery); 
</script>

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

Generate an array containing all N-digit numbers with a sum of digits equal to S

I encountered a problem with my code translation process. Despite finding solutions in other languages, when I converted them to javascript, the expected array was not created. const find_digits = (n, sum, out, index) => { if (index > n || sum & ...

Attempting the transformation of jQuery ajax requests to Angular's http service

I am looking to transition my existing mobile application from using jquery ajax to angularjs for handling user authentication with server-side validation. Here is the original jquery ajax code: function validateStaffUser(username, password) { var re ...

A guide on displaying a text file from a URL in a reactjs application

When utilizing the code provided below, I have successfully managed to display the content of a local text file on a webpage. However, when attempting to render a text file from a URL, the state becomes null resulting in an empty display. In order to ren ...

Upon registration, the user's information is successfully stored in the mongoDB database, even if the selected "username" is already in

I am currently working on a web application using the MERN stack. When registering a user with an existing email either through Postman or the front-end form, the user is not added to the database. The same logic is applied to check if the chosen username ...

There was an error parsing the sourcemap for js/popper.js in an ASP.NET MVC 5 project, causing devtools to fail

When attempting to use an AJAX request in my browser console to obtain an authentication token and redirect to my dashboard, I am encountering an issue. Clicking on the login/sign-in button does not result in any action. The link contains my email and pass ...

What error am I making in the Date calculator for the select box using Javascript/jQuery?

$(.dateselboxes) .change( function(){ var y; y=$("#year").val(); var m; m=$("#month").val(); var d; // check for leap year var isLeapYear; if(y%4==0) { if(y%100==0) { if(y%400==0) {isLeapYear=true;} else {isLeapYear=false;} } ...

Leveraging JQuery's parseJSON() function

Below is the code snippet I am working with: function responseLogin(response) { var newArray = jQuery.parseJSON(response); alert(newArray.AccountEmail); } When this code runs, it alerts the following message: {"AccountEmail":["Alphabets and numbers only ...

Objects of equal nature combine and sift through

I am looking to categorize objects based on their status ID and also retrieve data and CSR counts for each item. Each StatusName has multiple items: [ { "StatusId": 2, "StatusName": "ordered", " ...

Issue with calling function from props in React is not being resolved

There seems to be an issue with the function not being called when passed into a functional component. While the onSubmit function is triggered, the login(email, password) function inside the Login component is never executed. Despite placing console.log s ...

Challenges of positioning two div elements next to each other without adhering to the width of the container

Apologies for my limited knowledge of CSS and HTML; I am relatively new to this. I have gone through various questions and tutorials on how to align two divs side by side, but I seem to be facing difficulties in controlling the width of the divs in my cod ...

Why are my video files exhibiting inconsistent behavior?

I've encountered an issue with the code on my website where I'm trying to display a 40-second video. The video converter I used seems to have added extra video types, which may be causing the problem. Here's what the HTML code looks like: ...

Interactive navigation through scrolling with PHP onchange event

I need help with a PHP-related issue. I have a list of products that are generated dynamically using PHP. When a user clicks on one of the items in the list, the products are sorted. I also want the user to be smoothly scrolled to a new section of the page ...

AngularJS validation for minimum character count prevents character overflow

Encountering an unusual "issue". I've set up a form with a textarea that has both a minlength and maxlength validation. In addition, there's a straightforward character count displayed: <textarea ng-trim="false" ng-model="form.text" minlengt ...

React fails to display image on the server

One issue I'm facing with my React project on the server is that some images are not being displayed. Click here to view image description The console error message reads: ASGimagen.png:1 GET https://[url of my server]/autodiagnostico/cuadroanimado ...

When communicating with the backend in a React application, the data is not being successfully sent using axios. An error message stating "Unsupported protocol

My current setup involves using Express.js as the backend and setting up a proxy to the backend in the package.json file of my React.js project. Initially, I encountered an error when using the fetch method, so I switched to using Axios to resolve this iss ...

Determine the associated value for a given key within a TypeScript object

I have a structure like this: type newsItem = { img: string; slug: newsSlug; text: newsText; }; derived from an enum like this: export const newsEnum = { interesting: "Interesting", regions: "Regions", contradictory: " ...

The color of the letters from the user textbox input changes every second

My task is to create a page where the user enters text into a textbox. When the user clicks the enter button, the text appears below the textbox and each letter changes color every second. I am struggling with referencing this jQuery function $(function() ...

Is it possible for a Bootstrap modal dialog to overlay another dialog window?

<button class="btn" onClick="$('#firstModal').modal('show');">Click Here</button> <!-- Modal --> <div id="firstModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden=" ...

Adjust the size of a div container depending on the content it holds

If the element div.PageheaderDescription does not contain any img or div#cat-text, I'd like the height to be set to 0px to eliminate any white space. Below is my CSS code: .PageHeaderDescription { height: 320px; position: relative; width ...

The sticky navigation bar unexpectedly jerks and creates a glitch

For the past few days, I've been grappling with a persistent issue that seems to be causing glitches on my site, especially when viewed on my iPhone. The problem lies in the sticky navbar, which snaps to the wrong place and jumps too fast when scrolli ...