Navigate to the homepage section using a smooth jQuery animation

I am looking to implement a scrolling feature on the homepage section using jquery. The challenge is that I want the scrolling to work regardless of the page I am currently on.

Here is the HTML code snippet:

<ul>
  <li class="nav-item active">
    <a href="#home" class="nav-link p-0">Home </a>
  </li>
  <li class="nav-item">
    <a href="#about-us" class="nav-link p-0">About us</a>
  </li>
  <li class="nav-item">
    <a href="#references" class="nav-link p-0">References</a>
  </li>
</ul>

And here is the jquery function responsible for animating the scroll:

$(".nav-link").on("click", function (e) {
  e.preventDefault();
  var target = $(this).attr("href");
  $('html, body').animate({scrollTop: $(target).offset().top}, 800, 'linear');
});

When I click on a .nav-link while on the homepage (www.my-url.com), it scrolls smoothly as expected. However, if I am on another page like www.my-url.com/some-page and click on a .nav-link, the scroll animation does not work.

Is there a way to first navigate to the homepage before applying the scroll animation when clicking from a different page?

Any suggestions would be greatly appreciated.

Answer №1

implement this

<script>
document.querySelectorAll('a[href^="#"]').forEach(link => {
  link.addEventListener('click', function (event) {
    event.preventDefault();

    document.querySelector(this.getAttribute('href')).scrollIntoView({
      behavior: 'smooth'
    });
  });
});
</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

Forcing UTF-8 Encoding in JavaScript

I came across this helpful article: While following the advice of many others suggesting to use unescape(encodeURIComponent(srt)), I encountered issues. Attempting to convert the file obtained through XMLHttpRequest did not yield the desired results. Pri ...

How to make a letter stretch all the way down the paper?

As I'm creating a table of contents for my website, I was inspired by an interesting design idea that I came across: I am particularly drawn to how the T extends down and each section is numbered with the title wrapped around it. How can I achieve th ...

Ensure to check the input file for null values before proceeding

My task involves working with an input file: Razor: @Html.TextBox("archivo", "", new { type = "file",id = "archivo" } Html: <input id="archivo" name="archivo" type="file" value=""> I am trying to detect if the value of the input is null when a b ...

I am facing issues with my submit buttons as they are not functioning

Once I hit the submit buttons, there seems to be an issue with redirecting to another page. Could anyone assist in identifying the error within this code and why my buttons "typ1" and "cod" are not redirecting to the specified location? <?php inc ...

I want to display events from my database table on their corresponding dates using JavaScript and jQuery. How can I achieve this?

Using the FullCalendar plugin, I attempted to achieve a specific functionality, but unfortunately fell short of my goal. Below is the snippet of my scripting code: $('#calendar').fullCalendar({ //theme: true, header: { ...

Retrieve the JSON response from the server and store it in variables using jQuery's AJAX function with the `done

I am trying to retrieve a JSON response from the server upon clicking a button and then parse it into a div. However, I am struggling with how to accomplish this. <button type="submit" id="btPay" name="btPay"> Go for Pay ...

Universal customization for Material-UI Select

I am attempting to customize the appearance of a select component within a React project using MUI 5. Specifically, I want to modify the border size and color when the select component is in focus. While other components can be styled globally using styleO ...

Retrieve information from an express server using the fetch API

I am attempting to use the alert function to display a variable string in Express's .get() method and then send it using res. I want the alert to show "I am working fetch". This is my server.js var express = require('express'); var app = e ...

Transferring a JavaScript variable to JSP using AJAX

I'm struggling to figure out the correct syntax to pass a JavaScript variable named "textVal" to a jsp file. Here is my code snippet: function show(textVal){ AJAX.onreadystatechange = handler; AJAX.open("POST","service.jsp",true); AJAX.setR ...

JavaScript multiplying an array in HTML

Snippet of HTML code <input name="productCode[]" value="" class="tInput" id="productCode" tabindex="1"/> </td> <input name="productDesc[]" value="" class="tInput" id="productDesc" readonly="readonly" /></td> <input name="pr ...

What is the appropriate way to retrieve an array that has been stored in the this.state property?

https://i.stack.imgur.com/y9huN.jpgAs a newcomer to react, I have been exploring the react documentation on making Ajax calls. While the docs make it seem simple to retrieve JSON information and set it to a state variable, I've encountered some challe ...

Converting an HTML div to a string for export

In the process of developing my application, I am utilizing an angular widget to construct a dynamic dashboard. Here is the snippet of HTML code along with the associated JavaScript that enables this functionality: <div class="page" gridster="gridsterO ...

Searching by multiple parameters in Angular.js

I have a script that scans through a field and highlights the words related to the search input. I want this script to not only filter by title, but also by name. How can I adjust the code to filter both the title and name when searching? <li ng-repeat ...

Identifying the HTML elements beneath the mouse pointer

Does anyone know the method to retrieve the HTML tag located directly under the mouse cursor on a webpage? I am currently developing a new WYSIWYG editor and would like to incorporate genuine drag and drop functionalities (rather than the common insert at ...

PHP: How to Return a Multidimensional Array and Separate Variables Simultaneously

I am trying to send a 2D array with multiple individual variables from a PHP script to a JavaScript client using AJAX. Despite many attempts, I haven't been able to figure out how to include additional individual variables (like $var1, $var2, $var3) i ...

Different methods of displaying the next image from a URL without explicitly setting the dimensions

I am attempting to display an image in Next.js without specifying the width and height by using import Image from 'next/image';. It should be noted that the image is sourced from a URL, not a specific folder within the project. <Image si ...

Unable to place an absolutely positioned Div within relative parent containers

After applying the id "enterGame" with position: absolute, I noticed that the div disappears. Even when I tried adding position: relative to the body or html tag, the div remained invisible. The relevant code snippet is as follows: html { height: 10 ...

Add a border to the 'contenteditable' class in a Bootstrap table after it has been modified

Looking for help with JavaScript and jQuery! I have a script that creates an HTML table from a CSV file, using Bootstrap for styling. I want to add CSS or a border to a table cell after it has been edited, but my jQuery attempts haven't worked. Any su ...

What is the best way to implement a sub-menu using jQuery?

After successfully implementing a hover effect on my menu item using CSS, I am now struggling to make the sub-menu appear below the menu item upon hovering. Despite my efforts to search for jQuery solutions online, I have not been successful. Are there a ...

How can we use jQuery to animate scrolling down to a specific <div> when clicking on a link in one HTML page and then navigating to another HTML page?

I'm currently working on creating a website for my friend who is a massage therapist. Utilizing a bootstrap dropdown menu, I have added links to different treatments that direct to the treatment.html from the index.html page. Is there a way to creat ...