I am having trouble getting the smooth scroll feature to work on my horizontally scrolling website

Hello, I've added jQuery smooth scrolling to my website but it doesn't seem to be working correctly. Instead of scrolling smoothly, the site now scrolls horizontally to the right. I have already tried using smooth-behaviour but that did not solve the issue.

Here is the JavaScript code:

$(document).ready(function () {
  // Add smooth scrolling to all links
  $("a").on("click", function (event) {
    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      $("html, body").animate(
        {
          scrollTop: $(hash).offset().top,
        },
        800,
        function () {
          // Add hash (#) to URL when done scrolling (default click behavior)
          window.location.hash = hash;
        }
      );
    } // End if
  });
});

And here is the HTML code:

<img src="icon/logo.svg" alt="logo" class="logo">
<div class="navbar">
  <a href="#home" class="nav-a">Home</a>
  <a href="#about" class="nav-a">About</a>
  <a href="#works" class="nav-a">Projects</a>
  <a href="#documentation" class="nav-a">Documentation</a>
</div>

Answer №1

For a different approach, consider this suggestion,

Suggested Solution

Try implementing the scroll-behaviour property in your CSS.

html{
  scroll-behavior: smooth;
}

Additionally, structure your sections with unique IDs like this,

  <div id="home">
    <p>home</p>
    <p>home</p>
    <p>home</p>
    <p>home</p>
  </div>

html{
  scroll-behavior: smooth;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://i.sstatic.net/pDKtO.png" alt="logo" class="logo">
<div class="navbar">
  <a href="#home" class="nav-a">Home</a>
  <a href="#about" class="nav-a">About</a>
  <a href="#arb" class="nav-a">Projects</a>
  <a href="#doc" class="nav-a">Documentation</a>
  
  <div id="home">
    <p>home</p>
    <p>home</p>
    <p>home</p>
    <p>home</p>
  </div>
  
  <div id="about">
    <p>about</p>
    <p>about</p>
    <p>about</p>
    <p>about</p>
  </div>
  
  <div id="arb">
    <p>projects</p>
    <p>projects</p>
    <p>projects</p>
    <p>projects</p>
  </div>
  
  <div id="doc">
    <p>documentation</p>
    <p>documentation</p>
    <p>documentation</p>
    <p>documentation</p>
  </div>
  
  <p>navbar</p>
  <p>navbar</p>
  <p>navbar</p>
  <p>navbar</p>
  <p>navbar</p>
  <p>navbar</p>
  <p>navbar</p>
  <p>navbar</p>
  <p>navbar</p>
  <p>navbar</p>
  <p>navbar</p>
</div>

Alternative Approach

You can also utilize the .animate() method for smoother scrolling by targeting the body and html elements.

Incorporate a new attribute named target-toggle for your links

<a href="#" target-toggle="#home" class="nav-a">Home</a>

if($('[target-toggle]').length) {
  $('[target-toggle]').on("click",function () {
    var $target_value = $(this).attr("target-toggle");
    if($($target_value).length) {
      $('html, body').stop().animate({
        scrollTop: ($($target_value).offset().top)
      }, 1000);
    }
    event.preventDefault();
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://i.sstatic.net/pDKtO.png" alt="logo" class="logo">
<div class="navbar">
  <a href="#" target-toggle="#home" class="nav-a">Home</a>
  <a href="#" target-toggle="#about" class="nav-a">About</a>
  <a href="#" target-toggle="#projects" class="nav-a">Projects</a>
  <a href="#" target-toggle="#documentation" class="nav-a">Documentation</a>
  
  <div id="home">
    <p>home</p>
    <p>home</p>
    <p>home</p>
    <p>home</p>
  </div>
  
  <div id="about">
    <p>about</p>
    <p>about</p>
    <p>about</p>
    <p>about</p>
  </div>
  
  <div id="projects">
    <p>projects</p>
    <p>projects</p>
    <p>projects</p>
    <p>projects</p>
  </div>
  
  <div id="documentation">
    <p>documentation</p>
    <p>documentation</p>
    <p>documentation</p>
    <p>documentation</p>
  </div>
  
  <p>navbar</p>
  <p>navbar</p>
  <p>navbar</p>
  <p>navbar</p>
  <p>navbar</p>
  <p>navbar</p>
  <p>navbar</p>
  <p>navbar</p>
  <p>navbar</p>
  <p>navbar</p>
  <p>navbar</p>
</div>

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

Issue NG8001: ReadyToTalkComponent could not be recognized as a valid element - Module Angular 14 has already declared it

Upon updating to Angular 14, I ran into numerous errors, most of which were related to unknown elements. Despite declaring the component name under @NgModule in Declarations, the issues persisted. See the information below. ng version Angular CLI: 14.2.11 ...

Spin around revolving object

Trying to figure out how to animate a solar system using SVG. I've got everything set up except for the moon rotating around Earth. Any suggestions on how to make it work? <svg viewBox="0 0 500 500"> <!-- sun --> <circ ...

obtain data from JSON using JavaScript

Greetings! I am dealing with a JSON output that looks like this: "{ \"max_output_watts\": 150, \"frame_length_inches\": \"62.20\", \"frame_width_inches\": \"31.81\" }" I am using it in a functi ...

What is the best way to ensure a stable background image using CSS?

I have successfully created my navigation section and now I am working on the main body of the website. However, when I try to add a background image, it ends up appearing on the navbar as well. Can someone please assist me with this issue? Below is the HT ...

Dealing with problems in parsing JSON data returned from a jQuery AJAX

I am currently working with the GitHub API V3 and using the following code for making an AJAX call: $.ajax({ type:'POST', url: 'https://api.github.com/gists', data: JSON.stringify({ "public": true, "files": ...

Price and advantage in a single line of HTML code

Is there a valid reason for creating one-line HTML? Or is it better not to? I understand that reducing file size is a benefit, but we also need to consider the cost on the server of adding functions to generate one line HTML. Additionally, making changes ...

Tips for ensuring a function in Angular is only executed after the final keystroke

I'm faced with the following input: <input type="text" placeholder="Search for new results" (input)="constructNewGrid($event)" (keydown.backslash)="constructNewGrid($event)"> and this function: construct ...

I am interested in developing a Menu system that features different categories and subcategories

I am in need of assistance in creating a menu that includes both categories and sub categories. An example of what I am looking to achieve can be seen on the website www.boots.com If anyone has any suggestions or advice to offer, I would greatly apprecia ...

What could be the reason for my Node.js Express response coming back as empty?

While working on a registration system, I have encountered an issue. When errors occur in the form, I receive the correct error messages. However, when a user with the same email attempts to register and triggers 'res.json({error: 'email exists& ...

Organizing Angular project folders with the help of Node.js and Jade

I've been exploring different folder structures to ensure scalability as my project grows. While I found some useful resources, such as this one, I'm still struggling with how to actually implement these suggestions. Currently, I've adopted ...

Strict mode does not allow duplicate data properties in object literals within JavaScript

Challenge Description I am facing an issue with handling an optional variable called ByteRange. To accommodate this, I included 2 different URLs in the $resource. Upon doing so, I encountered the following error: Message: Error in parsing: "tools/tes ...

The results do not appear when using Bootstrap 3 Typeahead

I am currently utilizing Bootstrap 3 Typeahead in conjunction with an ajax call. The function is successfully returning the data, however, it is not displaying. Below is my code snippet: $('#txtComune').typeahead({ minLength: 2, ...

implementing dynamic navigation bar, when transforming into a dropdown menu using ReactJS

I am currently utilizing a navigation bar from a Bootstrap theme within my React project. The navigation bar includes an in-built media query that determines whether it should display as a dropdown menu or not, with a toggler to handle the dropdown functi ...

Designing rows and columns using Angular CSS within an ngFor loop

Is there a way to align items in a row or column based on conditions within an *ngFor loop? I want the input type to display on the next line if it is textarea, and on the same line otherwise. Check out this Stackblitz Demo for dynamically generated HTML ...

What is the method for adding 24 hours to a 12-hour timestamp while preserving the AM and PM designation?

I have created the following code to display real-time, but I am struggling with adding a timestamp that switches from 24-hour format to 12-hour format with AM and PM. setInterval(function() { var date = new Date(); var hours = date.getHours(); va ...

Ways to shut down a pop-up

Can someone assist me with how to close the bio-info popup and implement it in the code provided below? The HTML file: <ul class="ch-grid"> <li> <div class="bioinfo"> <h2>tooltips</h2> /div> The CSS file: .bioinfo { ...

What is the best way to add animation to the hide/show function?

<div class="overlay"></div> CSS: .overlay::after { position: fixed; top: 0; left: 0; width: 100%; content: ""; z-index: -1; height: 100%; transit ...

What is the process for adding text or HTML to a targeted DOM element using python with Selenium WebDriver?

I'm seeking guidance on how to use Python along with Selenium and WebDriver to insert text or HTML into a specific DOM element. Can anyone provide instructions on how to accomplish this task? ...

Uh-oh! There seems to be a problem with Chunk.entrypoints. It is recommended to utilize Chunks.groupsIterable and then

I encountered an error while running the script npm run watch cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --config=node_modules/laravel-mix/setup/webpack.config.js i 「webpack」: Watching enabled \ Buildi ...

Adjusting the appearance of internal components with material-ui icons

Currently working on a project using react and material-ui where I am looking to customize the styles of specific elements within components. An example is the ListItem component which includes primaryText, leftIcon among others, and my goal is to modify t ...