The functionality of jQuery smooth scrolling to an anchor is only effective when the page is at the top and there is

Currently, I am working on designing a simple one-page website featuring a fixed menu that smoothly scrolls to specific sections on the page upon clicking the menu items.

However, I have encountered an issue where the scrolling works perfectly only when the page is scrolled to the very top. If I first click on one menu item and then proceed to click another, the page will scroll to seemingly random positions instead of the intended anchors.

This problem arises specifically when using a jQuery script for smooth scrolling. Removing the script resolves the anchor linking issue but eliminates the smooth scrolling effect that I desire.

To better illustrate this problem, I have created a JSFiddle demonstration along with a brief video.

$(document).ready(function () {
$('a[href^="#"]').on('click',function (e) {
    e.preventDefault();

    var target = this.hash;
    var $target = $(target);

    $('html, body').stop().animate({
        'scrollTop': $target.offset().top - 50
    }, 900, 'swing', function () {
        window.location.hash = target;
    });
  });
});

Answer №1

Instead of utilizing the a element for bookmarking, consider using the div element and enclosing all relevant content within it; the block-element tends to perform better in this scenario.

// Smooth scroll to anchor-links
$(document).ready(function() {
  $('a[href^="#"]').on('click', function(e) {
    e.preventDefault();

    var target = this.hash;
    var $target = $(target);

    $('html, body').animate({
      scrollTop: $target.offset().top - 50
    }, 900, 'swing', function() {
      window.location.hash = target;
    });
  });
});
.menu-fixed {
  width: 100%;
  height: 50px;
  background-color: red;
  color: #fff;
  position: fixed;
  top: 0px;
  left: 0px;
  margin: auto;
  text-align: center;
}
.menu-fixed a {
  width: 20%;
  display: inline-block;
  line-height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="menu-fixed">
  <a href="#link1">Link 1</a>
  <a href="#link2">Link 2</a>
  <a href="#link3">Link 3</a>
  <a href="#link4">Link 4</a>
</div>

<p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc porta pellentesque velit. Donec mattis lacus in nisl volutpat dapibus... (truncated for brevity)
 ...congue efficitur imperdiet. Vestibulum nec commodo arcu. Curabitur cursus enim ut dapibus elementum.
  </p>

... continue with remaining content...

Answer №2

I have implemented the following modifications and now everything is functioning smoothly for me. I hope these adjustments prove to be helpful for you as well.

$(document).ready(function () {
    $('a[href^="#"]').on('click',function (e) {
        e.preventDefault();

        var target = this.hash;
        var targetHref = $(this).attr('href');  //MODIFICATION MADE HERE
        var $target = $(target);

        $('html, body').stop().animate({
            'scrollTop': $(targetHref).position().top   // MODIFICATION MADE HERE
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });
});

Answer №3

Give this a try:


$(document).ready(function() {
  $('a[href*=\\#]:not([href=\\#])').click(function() {
    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
        }, 1000);
        return false;
      }
    }
  });
});

This solution is guaranteed to be effective.

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

Apply a new class to an element's id using jQuery

Looking for a way to change the plus symbol to a minus symbol when clicked in my HTML code. <div class="col-3"> <a href="#tab-1"> <span class="plus" data-tab="tab-1">+</span> </a> </div> <div class="col-3"> & ...

Continuously I am being informed that the value is null

Check out this code snippet: var Ribbon = /** @class */ (function () { function Ribbon(svg) { // Code here... } Ribbon.prototype.init = function() { // Initialization code here... }; Ribbon.prototype.updateR ...

When the content is clicked, it slides up

This is the code snippet I have been working with: $("a.shownav").on("click", function(){ $("div.nav").slideToggle(); }); However, I encountered an issue where I want the div.nav part to slide up when I click on other areas of the page except for the ...

Tips for properly styling the input type range element

Is there a way to fix the issue with my input type="range" styling using linear-gradient when the variable is set to 75%? It seems to be behaving incorrectly. body{ background: green; } .wrapper { width: 20vmin; } input { widt ...

What could be causing the issue with React Router not functioning properly in Material UI?

I'm currently working on creating a tab and adding routing inside the first tab. However, I am facing an issue where the desired page does not display after clicking on the link. Strangely, upon refreshing the page, the corresponding page appears as e ...

Is there a way for me to retrieve the data returned from a worker thread?

In my quest to understand how worker-threads function, I've come across this useful example: https://github.com/heroku-examples/node-workers-example.git REMINDER: Ensure Redis is installed and running for this example My primary challenge lies in r ...

Is there a way to keep track of changes in multiple dropdowns without having to create a separate JavaScript function for each one

I'm looking for a way to dynamically add more dropdowns as my website grows without having to keep adding new functions to the JavaScript code. Is there a solution for this? Currently, I can add additional functions to the JavaScript like this: ...

Fade-in effect applied to images upon exposure

Is there a way to fade in an image based on the percentage scrolled, rather than a set number of pixels? I want my website to be responsive and adjust to all screen resolutions. Or perhaps is there a method to have the image fade in when it enters the fiel ...

Display the variable value in an HTML format following the submission of a request to an API using NODE JS, express, and jquery

Seeking assistance with completing a straightforward task: Creating an HTML AJAX link that triggers a Node.js API call to retrieve a value, wait for the response, and then display the value in HTML, JS, or PHP. After clicking on the "Get My Value" link be ...

Displaying nested JSON data in a user interface using React

I have a complex nested JSON structure that I am using to build a user interface. While I have successfully implemented the first part, I am encountering difficulties with the second part. My Objective The nested JSON displays parent elements and now I a ...

Encountering a Zone.js error when trying to load an Angular 7 app using ng serve, preventing the application from loading

Scenario: Yesterday, I decided to upgrade my Angular app from version 5.2.9 to 6 and thought it would be a good idea to go all the way to 7 while I was at it. It ended up taking the whole day and required numerous changes to multiple files, mostly due to R ...

Add custom scripts to individual components within a Vue.js application

After extensive searching, I still can't seem to find a solution to my current issue. My focus is on a Vue project with vue-cli, where I need to inject various scripts into different pages (leveraging vue-router). Here are more specific details: Thi ...

Delayed hover dropdown navigation menu powered by Bootstrap

I am experimenting with creating a bootstrap dropdown menu that opens and closes on hover, but only after a 250ms delay for desktop devices. Custom JavaScript: $(document).ready(function() { if ($(window).width() > 767) { $(".dropdown-toggl ...

Display text on the screen with a customized design using JavaScript's CSS styles

I need help with printing a specific page that contains some information designed in print.css. I want to print this page, including an image, with the same style. function printContent() { var divContents = document.getElementById("terms").innerH ...

Is it possible for me to pass a value through props that is not currently stored in the state?

Within the realm of Reactjs, imagine a scenario where there exists a <Parent> component containing state and a variable named foo, which is either 'global' or local to Parent. The question arises: Can we pass foo as props using <Child v ...

The onclick handler fails to function following the injection of html using jquery AJAX

After using ajax to inject HTML into my page, the onclick handler on a specific part of that injected HTML does not seem to be functioning... Specifically, I am referring to this image... < img class="close_row" src="img/close.gif"/> In jQuery, I ...

What is the best way to keep the navbar contained within the parent div (hero image) no matter the size of the screen?

After working on adjusting my website layout for different screen sizes, I encountered an issue with the navbar overflowing the parent image when viewed on my laptop. Despite trying both relative and absolute positioning for the .navbar element and setting ...

Show the form for user input

I have an HTML code for a form that requires input. Once the 'OK' button is clicked, the values are sent to a PHP script using $_POST. Is it possible to display the same form again if the input format is incorrect, but do so only within my PHP sc ...

Internet Explorer and CSS: How to eliminate a highlight that pops up when the button is clicked

Could you please check out this website in Internet Explorer (I've tried it on the latest version as well as older versions.) On the above link, there are two circular buttons at the bottom of the page. In IE, when you click on a button, a semi-trans ...

What is the process of integrating an HTML web component with an HTML file? Can I use innerHTML = foo("myfile.html") to achieve

Using HTML web components allows me to define their code using this method: this.innerHTML = `<h1></h1>`; However, I find it cumbersome as I do not have access to the Emmet Abbreviation feature which slows down my component creation process. ...