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

What was Douglas Crockford trying to convey with the term 'created in an alternate window or frame'?

What did Douglas Crockford mean when he mentioned that the is_array() test might not correctly identify arrays created in a different window or frame? var is_array = function (value) { return value && typeof value === 'object&apos ...

How come the focus doesn't work when altering the CSS code simultaneously?

My attempt at creating a user interface involved an issue where the input field was not visible initially. After clicking the button, the input would appear on the screen, and I wanted to automatically focus on it. This is what I tried to achieve: Initial ...

Combine the commands gotoIf and storeAlertPresent into a single string in Selenium IDE. Can you help me with this

Could you please fix the following command? gotoIf | storeAlertPresent==false | continue This command is not functioning properly. Additionally, I am unable to use more than one string in Selenium IDE. ...

What is the best way for me to send a confirmation response to my API once a user has clicked on the activation link

I have been attempting to send a confirmation message to my API after clicking on the activation link, but despite numerous attempts, I have not been successful. Please see the activation link below: <script type="text/javascript> ...

Incorporating a divider into a Material-UI MenuItem causes an additional border

I needed a way to separate the MUI MenuItem using a divider, but it resulted in an extra border around the item where the divider was placed. The highlighted section in the image shows the item that has the divider= true setting and the extra border. Is th ...

React useEffect only retrieves the last element of an array object

I am facing an issue where React seems to only save the last element in my array. Even though I have two elements, when mapping over them, only the last element is being placed in the hook each time. React.useEffect(() => { if (bearbeiten) { handleCli ...

Issue with Bootstrap 3: Element refuses to remain within the defined width of the div container

While utilizing bootstrap 3 within a small div, I noticed that when I enlarge the window by dragging it horizontally, the fields (username and password input fields) that should remain inside the div end up shifting towards the center of the window. Can an ...

Boxes that change and adapt to the user's input

Need guidance on a tricky problem! I am working on a form to input various cities that the user wants to visit. The form currently consists of one form box and a submit button. My goal is to allow the user to enter multiple cities by clicking an "Add 1 ...

Dealing with asynchronous requests in Axios: A guide to solving the challenge

I'm working on a page named _id.vue in my Nuxt.js project: <template> <div class="wrapper"> <HeaderApp> <DivHeaderMenu> </DivHeaderMenu> </HeaderApp> <CenterContentDinamicFirmeni ...

The Console.log() function displays the current state and value of a promise object within the Q library

Whenever I attempt to print a promise object from Q, the result that I receive is as follows: var Q = require('q'); var defaultPromise = new Q(); console.log('defaultPromise', defaultPromise); defaultPromise { state: 'fulfilled& ...

Angular Universal functioning fine on local host, yet encountering issues on Nginx Server

I recently developed a project with Angular Universal. After building the project, it generated files such as browser, server, server.js, and prerender.js. I am curious to learn how I can run this project on an nginx server. Currently, I create a build o ...

Unselect all checkboxes except for the one that was clicked

In a project, I have 3 checkboxes that are interconnected and when one is clicked or checked, I want the others to be cleared while keeping the clicked checkbox checked. This behavior is similar to radio buttons but I cannot use radio buttons due to client ...

Develop a form containing a date input in a special character-free format, along with a validation feature

I am looking to design a form that necessitates users to input a date in the following format: "ddmmyyyy". No slashes, dots, or any other special characters should be included. Only entries matching this specific format will be accepted as valid, any other ...

Is it possible to execute a program on MacOS through a local HTML website?

Are there any straightforward methods to launch Mac programs using HTML? I've created an HTML page featuring a text field and several buttons. The goal is for users to enter a code (numbers) that will then be copied to the clipboard. By clicking on t ...

Populate an HTML layout with MySQL information and dynamically add the content to the page using JavaScript

I'm facing a challenge with creating an about us page for a website. I am using a template to structure the page and I want to populate it with MySQL data. I have enclosed the entire <div> of the personcard within a <script> tag, but the p ...

Using @extend with numeric classes in Bootstrap 5: A step-by-step guide

I am looking to migrate some classes from Bootstrap 4 to 5 because some of the Bootstrap classes are no longer usable, especially in utilities. I am using SASS so I can utilize @extend for this process. https://i.sstatic.net/dEDCw.png For classes .text-l ...

Creating a grid layout by designing boxes using CSS and HTML

I'm in the process of creating a homepage and I'd like it to resemble this design: (not the best quality, but the software I used was subpar (I miss mspaint)) Originally, I used buttons which made linking and customization easy, but I encounter ...

What could be causing my Ajax function to malfunction?

I've been attempting to incorporate a form that sends two javascript variables to a php script and displays the result in a new Div on the same page using an ajax function. Unfortunately, it's not functioning as expected. Here is the code snippe ...

Unable to trigger dispatchEvent on an input element for the Tab key in Angular 5

In my pursuit of a solution to move from one input to another on the press of the Enter key, I came across various posts suggesting custom directives. However, I prefer a solution that works without having to implement a directive on every component. My a ...

A guide on creating a clickable polygon in Vue.js using Konva

Is there a way to create an interactive polygon in Vue Konva where I can set each corner with a click? I haven't been able to find any resources other than the v-polygon which only creates predefined polygons. ...