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 create multiple links using jQuery that will automatically scroll down to the specific treatment section on the new treatment.html page when there are multiple treatments available?

Apologies for any language errors. I am doing my best as English is not my first language.

I am quite inexperienced with JavaScript and jQuery, this being my first attempt at using them.

I came across this code snippet, but it doesn't seem to be working correctly:

<!-- Treatment scrolldown -->
$("html, body").animate({ scrollTop: $('#treatment1').offset().top }, 1000);

$("html, body").delay(2000).animate({scrollTop: $('#treatment1').offset().top }, 2000);
<!-- End Treatment scrolldown -->

Answer №1

Consider trying out the code snippet below:

<div id="content">

    <ul>
        <li><a href="page1.html" data-section="section1" class="link-button">Page 1 Section 1</a></li>
        <li><a href="page1.html" data-section="section2" class="link-button">Page 1 Section 2</a></li>
        <li><a href="page2.html" data-section="section1" class="link-button">Page 2</a></li>
    </ul>

    <script>
        $(function () {

            $(".link-button").click(function (event) {
                event.preventDefault();

                var href = $(this).attr("href");
                var section = $(this).data("section");

                $("#content").load(href, function () {
                    $("html, body").animate({ scrollTop: $("#" + section).offset().top }, 1000);
                });

            });
        });
    </script>

</div>

Ensure that jQuery is included before the script for it to work correctly.

Answer №2

Don't forget, HTML comments cannot be used inside JavaScript.

Make sure to enclose your code with a script tag.

Remember to execute this within a self-executing function, such as the document ready event.

Additionally, don't forget to include jQuery before your script block.

For example:

<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>

<script>
$(document).ready(function(){
    $("html, body").animate({ scrollTop: $('#treatment1').offset().top }, 1000);

    $("html, body").delay(2000).animate({scrollTop: $('#treatment1').offset().top }, 2000);
});
</script>

Lastly, be sure to check the browser console for any errors that may come up.

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

Delete the option to alter button in the Jasny file input tool

I recently incorporated the Jasny Fileinput Widget into my existing form. However, I noticed that when I select a new file, it displays two buttons: Change and Remove. In this case, I believe the Change button is unnecessary and would like to remove it com ...

Including folders recursively using Node.js

Currently, I am in the process of setting up test automation using yarn, selenium, and node js. In the wdio.conf.js configuration file, there is a requirement to specify a specs array that contains strings representing paths to various js files for executi ...

I'm new to Angular, so could you please explain this to me? I'm trying to understand the concept of `private todoItems: TodoItem[] = []`. I know `TodoItem` is an array that

//This pertains to the todoList class// The property name is todoItems, which is an array of TodoItem objects fetched from the TodoItem file. I am unable to make it private using "private todoItems: TodoItem[] = []," is this because of Dependency Injectio ...

The picture above just won't stay within the div

Ensuring my website is responsive across all devices has been a priority for me. However, I have encountered an issue where, upon scaling down the size of the web browser, an image positioned within a div starts to overflow. While attempting to address thi ...

Utilize the ::before selector to insert white spaces

I attempted this solution, but unfortunately it did not produce the desired outcome: .stackoverflow::before { font-family: 'FontAwesome'; content: "\f16c "; } <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-aw ...

Approach for checking duplicates or empty input fields through PHP, AJAX, and JavaScript

Looking for a solution to validate and check for duplicate values when listing, creating, or deleting products using a REST API. I tried using rowCount in the php file to check for duplicates but I feel there might be a better approach that I am missing. N ...

What is the best way to implement two distinct global CSS styles for separate pages in Next.js?

I'm looking to give my website a fresh look by creating two different global CSS styles. Is it possible to use one CSS style for the old pages and another for the new pages? ...

Tips on adding style to your jQuery autocomplete dropdown

I am currently utilizing jQuery autocomplete functionality. I have configured it to communicate with a service and retrieve records: <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1 ...

"Counting the clicks on the filter button in React

I have: var RightPanel = React.createClass({ componentDidMount: function () { this.load(); }, load: function(){ }, render: function () { return ( <div> <div className="row"> ...

Looking for some advice on tackling this JavaScript challenge - how can I effectively split an array?

Hello everyone, I recently started learning javascript and I'm facing a challenge with the following problem. Below is the code I've written so far and I would greatly appreciate any feedback on where I may be going wrong and how I can solve this ...

Alternating CSS Designs for Displaying Multiple Mysql Query Results

I have a website where users can search for a specific product in their location, and the site will display a list of results. if(isset($_POST['zip'])){ $qry="SELECT business_id FROM ".TBL_BUSINESS." WHERE zip LIKE '%".$_POST['zip&apos ...

Create a regular expression that matches a combination of alphabets and spaces, but does not allow for

Can anyone provide a regular expression that allows for a combination of alphabets and spaces, but not only spaces? After searching extensively and reading numerous articles, I came across the expression /^[a-zA-Z\s]*$/, which unfortunately permits j ...

Alert-Enabled Random Number Generation Tool

I'm struggling to create a program that randomly generates a number between 1 and 20. If the number is less than 10, it should display "fail," and if it's greater than 10, it should display "success." I can't seem to figure out where I went ...

Listener document.addEventListener (function() {perform the function as shown in the illustration})

Currently facing an issue that I'm struggling to resolve, attempting to execute a code snippet from the ngcordova website without success. While using the plugin $cordovaInAppBrowser.open ({... it generally functions well until the inclusion of the ...

Implementing JavaScript functionality upon page load with ASP.NET

I have come across a situation where I am trying to integrate working code (jQuery/Javascript) that makes an API call and sends data to it. The API service then responds with a success or failure message based on the data insertion into the API db. Everyth ...

Encountered an issue while trying to extract data from state - property of null cannot

I'm facing an issue trying to show a navigation item only when a specific flag is true. The problem arises when I attempt to extract data from it, as it returns undefined. Below is the code snippet I have created for this scenario: let navigate = useN ...

Placing jQuery in the lower part of my HTML templates lacks adaptability

Lately, I've been optimizing my templates by placing the jQuery code link at the end of the template files to ensure fast page load speeds. Along with that, I have specific javascript modules reserved for certain pages that are included within the con ...

Unique loading animations are assigned to each individual page within the Next.js framework

Is there a way to have unique loading animations for each of my website pages during the loading process? How can I achieve this? I've attempted to put the loading component on the page component directly, but it doesn't seem to work: //Page com ...

What is the best method to deactivate zoom in/out buttons using JavaScript?

As a newcomer to Phonegap, I've managed to implement zoom in/out functionality using websettings in the .java file. However, I now face a challenge where I need to disable/enable the zoom in/out buttons and stop scrolling at a specific point. I attemp ...

The dimensions of the background for a span element

I have a span element with a background-color applied to it. Is there a way to adjust the size of this specific background? I attempted using background-size: auto 2px;, but it did not produce the desired effect. I am looking to make the background color ...