What are some ways to implement smooth scrolling when a navigation link is clicked?

I have a total of 3 links in my navigation bar and every time they are clicked, I want the page to smoothly scroll down to their designated section on the webpage. Although I have already set up the anchors, I lack experience in scripting to create the smooth scroll effect. Can someone guide me on what steps I should take? Additionally, I have prepared a JSFIDDLE for reference: https://jsfiddle.net/d9oxdxbo/

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <link href='https://fonts.googleapis.com/css?family=Roboto' rel='stylesheet'>
    <title>
    </title>
  </head>
  <body>
    <!-- Navigation Bar -->
    <ul>
      <li>
        <a href="test_webpage.html#about">ABOUT
        </a>
      </li>
      <li>
        <a href="test_webpage.html#coupons">COUPONS
        </a>
      </li>
      <li>
        <a href="test_webpage.html#feedback">FEEDBACK
        </a>
      </li>
    </ul>
    <img src="https://preview.ibb.co/dr3y7v/vintage.png" height="660px" width="100%">
    <h2>
      <span style="background-color: rgba(26, 102, 255, 0.75)">BRINGING YOU CONVENIENCE
      </span>
    </h2>
    <h3>
      <span style="background-color: rgba(26, 102, 255, 0.75)">SINCE THE 2000's
      </span>
    </h3>
    <div id='about'>
      <a id="about" name='about'>
        <div id='opaque'>
          <img src="https://preview.ibb.co/bS5nja/gas_station_hero_image.jpg" height="680px" width="100%">
        </div>
        <h4>WHO WE ARE
        </h4>
        <div id='divp2'> 
          <p>WE ARE A SMALL CONVENIENCE STORE LOCATED IN THE HEART OF CARY, NORTH CAROLINA. WE SPECIALIZE IN CRAFT BEER AND EXQUISITE WINE. WE HAVE ALL YOUR QUICK GROCERY NEEDS. WE HAVE THE BEST PRICES IN OUR AREA GUARANTEED! COME VISIT US FOR A TRULY ENLIGHTENING EXPERIENCE! WE ARE ON GOOGLE SO IF YOU WANT TO SEE OUR REVIEWS OR GIVE US ONE, YOU CAN!
          </p>
        </div>
        <div id='divp'>
          <p>YOU MIGHT BE WONDERING, WHY SHOULD I COME HERE? WHAT MAKES THIS GAS STATION DIFFERENT FROM OTHER GAS STATIONS? WELL, WITH EXCELLENT STAFF, LOW PRICES, AND CLEAN FLOORS, THE BETTER QUESTION SHOULD BE, WHY SHOULDN'T I COME HERE! WE HOPE YOU COME TO OUR STORE AND HAVE A FABULOUS EXPERIENCE. IF YOU DO EXPERIENCE ANY DIFFICULTIES DURING YOUR TIME HERE, PLEASE FEEL FREE TO CONTACT THE MANAGER. HE WILL RESOLVE YOUR COMPLAINTS IN NO TIME!
          </p>
        </div>
      </a>
    </div>
    <div id='coupons'>
      <a id="coupons" name='coupons'>
        <div style="float:left">  
          <img id='myImg' src="https://preview.ibb.co/jBYUxv/coupon1.png" id="i1" height="300px" width="600px">
          <div id="myModal" class="modal">
            <span class="close">×
            </span>
            <img class="modal-content" id="img01">
            <div id="caption">
            </div>
          </div>
        </div>      
        <div id='pformat'>
          <p>COUPONS FOR YOU!
          </p>
        </div>
      </a>
    </div>
    <div id='feedback'>
      <a id="feedback" name='feedback'>
      </a>
    </div>
  </body>
</html>

CSS

body {
    margin: 0px;
  }
  ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: mediumblue;
    font-family: monospace;
    font-size: 15px;
    text-align: center;
    width: 100%;
    top: 0;
  }
  li {
    display: inline-block;
  }
  ...

JS

// Get the modal
var modal = document.getElementById('myModal');
// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById('myImg');
...

Answer №1

Experiment with this code snippet for your anchor element

<script type="text/javascript">
$(document).ready(function() {
$('a'). Click(function(e) {
    e.preventDefault();
    $('html, body').animate({
        scrollTop: $('the link div').offset().top}, 'slow'); 
});
});
</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

Troubleshooting: Why Won't My Basic JQuery POST Request Work?

Can someone help me figure out how to use JQuery to send a POST request and display the data in a PHP file? Here is the HTML file: <html> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> ...

Unable to find module reference "three" at 137

Returning to an older project, I realized that nothing was loading. When I checked the console log, this is what I found: Uncaught TypeError: Failed to resolve module specifier "three". Relative references must start with either "/", "./", or "../". In my ...

It appears that the jQuery script is not loading properly

For my wordpress site, I have integrated jQuery using the wp_enqueue_script function along with the jQZoom script. In the header of my site, you can find the following lines in this order: <link rel='stylesheet' id='jQZoom_style-css&apo ...

Submitting selected options from radio buttons to the server-side using HTML

I'm facing a challenge that requires some guidance. Here is the html code I am working with: Avatar: <br /> <input type="radio" id="avatar" name="avatar" value="Option1"/><img src="" alt=""> <input type="radio" id="avatar" name ...

The 'checked' property cannot be bound to 'mat-button-toggle' as it is not recognized as a valid property in Angular 9

I am encountering an issue with my Angular 9 application. I have integrated angular-material and imported the MatCheckboxModule correctly in the module. Here is the version of the material package I am using: "@angular/material": "^10.2.0&q ...

Unable to navigate using react-router after logging out without a page refresh

In my logout approach, everything seems to work fine - there are no errors in the console, localHistory is cleared successfully, but for some reason it cannot navigate to the login page without refreshing the current page. const handleLogout = () => { ...

Tips for sending a set to a directive in angular.js?

Forgive me for my confusion. I am passing the name of a collection to my directive: <ul tag-it tag-src="preview_data.preview.extract.keywords"><li>Tag 1</li><li>Tag 2</li></ul> This is how the directive is defined: a ...

Unable to send form data to app.js

Although a similar question has been asked before, I haven't been able to find a solution that works for me. I've been attempting to send HTML form data to my app.js file. Below is my index.handlebars file: <form method = 'post' a ...

How can you extract the text associated with the chosen value in a dropdown list implemented in JavaScript?

Hello, I've been having difficulty extracting the value from a dropdown list created using the FacetWP plugin. Despite extensive research and numerous attempts using various methods to retrieve the text value from the list, I have not been successful. ...

Tips for sorting through JSON Data to isolate a particular day

I developed a Food-App that displays a different menu every day. I retrieve the local JSON Data using Axios and attempt to filter the mapped menu with .filter. My issue lies in not being able to filter specific days. I attempted to restructure the JSON Da ...

Convert a .xlsx file using unoconv into an image file such as png format

I have successfully installed unoconv on my Ubuntu 14.04 64-bit system. My goal is to convert the first sheet of an .xlsx file into an image format like png or jpg. After attempting the following commands: unoconv -l & 9998 ## this command starts th ...

Ways to include a CSS file path in a link tag from an npm package

I have recently installed a package using npm. npm install lightgallery Now, I am trying to fill the href attribute of a link with the css file directory of this package. Here is what I have so far: <link rel="stylesheet" href="/node_mod ...

Issue: Angular 14 - Validators Not Resetting in Nested FormGroup

I am currently working on implementing a nested FormGroup. However, I have encountered an error when attempting to reset the form. Here is the structure of the form: form: UntypedFormGroup; this.form = this.fb.nonNullable.group({ f1: [''], f2: ...

Sending the Image ID to the URL segment

I'm currently working on a project where I need to implement a functionality that allows users to click a button to load the next image from a database query result. However, I also need this action to redirect to a new page and not disrupt the layout ...

Real-time functionality is not supported by Firebase functions

I've set up a firebase query within a method in VueJS: data: {this.todaysEvents}, methods : { getTodaysEvents (day) { this.todaysEvents = [] const events = db.ref('calendar') const query = events.orderByChild('da ...

Uneven column widths in Bootstrap 4 tables

I'm updating a project to Bootstrap 4. Previously in Bootstrap 3, all three columns were the same width. However, in Bootstrap 4, the first column is wider while the other two columns are squished together on the far right side. Here is how it looked ...

Transforming a Bootstrap 4 HTML project into Angular 9

After stumbling upon a beautiful HTML template that caught my eye, I realized it was built using Bootstrap. Luckily, I came across tutorials on how to convert such templates into Angular 6 projects, making the process seem quite straightforward (like this ...

Syntax for retrieving response with jQuery AJAX

Currently, I am in the process of working on an AJAX request that triggers a URL when a specific button is clicked. The fundamental aspects are running smoothly, ensuring that the GET request is activated towards the URL upon button click. I have also cros ...

What is the method for setting a default value for a disabled input?

<input type="checkbox" disabled="disabled" checked="checked" name="is_ok" id="id_is_ok"/> Is there a way to set a default value for this disabled input? I've noticed that if this field is disabled and I make edits to my data, the changes are n ...

Utilizing Scrollify for seamless section scrolling with overflow effects

I have been experimenting with the Scrollify script (https://github.com/lukehaas/Scrollify) and facing an issue where my sections are longer than the user's screen, requiring them to scroll down to view all content. However, Scrollify doesn't al ...