Navigate to designated part of a website using HTML and CSS styling

Consider the following JavaScript code:

//Scroll Down button
$(window).scroll(function () {
if ($(this).scrollDown() > 100) {
$('.containerScroll').fadeIn('slow');
} else {
$('.containerScroll').fadeOut('slow');
}
});

$('.containerScroll').click(function () {
$('html, body').animate({
scrollTop: 0
}, 1500, 'easeInOutExpo');
return false;
});

This script is responsible for animating a back-to-top button where clicking it scrolls the user back to the homepage with a smooth transition. What if we want the button to take the user to a specific page instead of just the homepage? How can we modify the code to achieve this functionality?

In the accompanying HTML file, the link is set up as follows:

<a href="#about" class="containerScroll">
<div class="first-scroll"></div>
<div class="second-scroll"></div>
</a>

The current setup directs the user to the about section when the button is clicked. If you want the button to navigate to a different page on the website other than the homepage, what changes need to be made in the JavaScript code? Let's brainstorm some solutions.

Answer №1

back to the top

window.scrollTo({
  top: 0,
  behavior: 'smooth'
});

scroll to element

const scrollElement = getElementById("someElement");
//you can achieve this using jquery as well
element.scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});

Reference: scrolIntoView

Reference: scrollTo

Answer №2

To adjust the scrollTop attribute to match the offset of any desired element, follow this example:

$('html, body').scrollTop($('#about').offset().top);

This code snippet will align the scrollTop position with the top of the element identified by the about ID.

Alternatively, you can incorporate animation as demonstrated in your previous instance:

$('html, body').animate({
    'scrollTop': $('#about').offset().top
}, 1500);

Click here for a live demo

Experience smooth scrolling on this demo page

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

How to access a value from a for-loop in JavaScript beyond its scope

Hello there! Within nested json-files, I have been utilizing the following function for iteration: function organizePeopleGroups(People, container, parentObject) { _.each(People, function (item, index) { var peopleGuid =[]; for (var p ...

Simple and quickest method for incorporating jQuery into Angular 2/4

Effective ways to combine jQuery and Angular? Simple steps for integrating jQuery in Angular2 TypeScript apps? Not sure if this approach is secure, but it can definitely be beneficial. Quite intriguing. ...

Converting a JSON array to C# and vice versa in Xamarin Forms

I've been struggling to send a C# object as JSON array to an API endpoint. I feel like I'm going crazy trying to solve these issues. Here's a sample of the JSON data: Array ( [user_id] => 0002323445635 [order] => {"order":{" ...

Extracting data from web pages using JavaScript and PHP

Using the following script, I am able to scrape all the items from this specific page: $html = file_get_contents($list_url); $doc = new DOMDocument(); libxml_use_internal_errors(TRUE); if(!empty($html)) { $doc->loadHTML($html); ...

Prevent horizontal scrolling and bouncing on iOS devices without using overflow hidden

I've been on the lookout for a way to stop horizontal scrolling/bounce effect on iOS, but my search has been in vain. It's quite surprising that there doesn't seem to be a solution out there. Unfortunately, setting overflow hidden is not an ...

Starting object arrays in Angular 6 using ES6

As someone who is just starting out with javascript, I have encountered a challenge with a nested class structure. Specifically, I am looking to initialize an array of EventDate objects and assign it to 'this.dates' within the CustomerEvents cons ...

Error: Attempting to access property 'question' of an undefined value

Trying to render information from a local .json file using Javascript functions, I encountered an error in the console for const answer despite being defined. I temporarily commented it out to test the function, only to receive the same TypeError for quest ...

How can I display a JSON list of results in an IEnumerable type in a ViewBag using MVC?

My goal is to retrieve a list result in the type of IENumerable within the existing ViewBag that already contains a list. In the controller's action method, I am returning the list using ViewBag- [HttpGet] public ActionResult RangerCard() { var ...

React's constant rerendering of an overflowed component results in a jarring page jump

To view the code as a reference, click here. After pressing the button, the state changes and #container1 gets replaced with #container2. Despite this change, the page height remains constant and the outer containers maintain their original height. Howeve ...

A comprehensive guide on creating a package that combines an href link with an <li> element

I am currently using the <li> tag to display href links. The issue I am facing is that when I click on the 'box,' it does not directly link to another page. Instead, I have to click on the href link for it to redirect to another page. Is th ...

Tips for displaying a loading message during an AJAX request?

My AJAX function is set up like this: function update_session(val) { var session_id_to_change=document.getElementById('select_path').value; $.ajax({ type: "GET", url: "/modify_path/", asy ...

Tips for preventing the direct copying and pasting of JavaScript functions

Repeating the process of copying and pasting functions such as loadInitialValue(), loadInitialValue2(), loadInitialValue3(), is quite monotonous. This is the repetitive code snippet that I have been working on (when you click on "Mark as Read," the title o ...

How can I prevent duplicate IDs when submitting a form through AJAX within a while loop?

While submitting a form using Ajax within a while loop, I encountered an issue where the same form ID is being used multiple times due to the loop. As a result, the form only submits once. I believe that I need to generate a unique ID for each iteration of ...

Populate Input Field Based on Dropdown Selection

My goal is to retrieve the value of "hargaJual" when I choose an option. However, when I add a new row to the table and select a different option, only the first row's "Harga" value changes while the second row remains empty. Take a look at the outco ...

perform loading of dynamic JSON data in Grunt

Can a JSON file be loaded from a dynamic source for localisation purposes? grunt.file.readJSON('src/locales/<%= grunt.task.current.args[0] %>/i18n.json'); A sample section of the Gruntfile is as follows: module.exports = function(grunt) ...

Emphasize certain terms within a text field using Angular 8

I need assistance with selecting specific words from a textarea and generating bootstrap chips. My goal is to highlight the chosen words using various background colors. https://i.sstatic.net/3Rw2z.png export class SearchComponent implements OnInit { c ...

What are the steps to develop an ElectronJS application that displays "Hello world!" in the console after a button click?

Can anyone offer a helping hand? From the depths of imagination to the realms never before conceived by humans. Check out this HTML snippet: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Hell ...

Adjusting the height of an element in AngularJS based on its width dynamically

I am working on a table that is generated using ng-repeat, and I want to ensure that each td in the tbody is square. Since all the tds have an equal width, I only need to adjust the first one. However, the size of the table and td will change when the wind ...

Error: An unexpected identifier was found within the public players code, causing a SyntaxError

As a newcomer to jasmine and test cases, I am endeavoring to create test cases for my JavaScript code in fiddle. However, I'm encountering an error: Uncaught SyntaxError: Unexpected identifier Could you guide me on how to rectify this issue? Below is ...

Click on a specific image in a table using Cypress with a specific source URL

I need help with a query for Cypress regarding a table of items, each item having active (blue) and not active (black) images. How can I set up this query? Below is an image of the table list: https://i.stack.imgur.com/74qzb.png And here is the HTML code ...