Tips for automatically scrolling to the top of a page when a jQuery vertical tab menu is clicked

Here is the link to my demo: . I am attempting to make the page scroll when clicking on the vertical tab.

//script 1 $(document).ready(function(){

    if (
        $('ul#verticalNav li a').length &&
        $('div.section').length
    ) {
        $('div.section').css( 'display', 'none' );
        //$('ul#verticalNav li a').each(function() {
        $('ul#verticalNav li a').click(function() { 
            showSection( $(this).attr('href') );
        });
  // If hash found then load the tab from Hash id
        if(window.location.hash) 
        {
   // To get the div id
           showSection( window.location.hash);
        }
        else // If no hash found then default first tab is opened
        {
            $('ul#verticalNav li:first-child a').click();
        }
    }
});
</script>

//script 2

function showSection( sectionID ) {
    $('div.section').css( 'display', 'none' );
    $('div'+sectionID).css( 'display', 'block' );
}
$(document).ready(function(){

    if (
        $('ul#verticalNav li a').length &&
        $('div.section').length
    ) {
        $('div.section').css( 'display', 'none' );
        //$('ul#verticalNav li a').each(function() { // No need for each loop
        $('ul#verticalNav li a').click(function() { // Use $('ul#verticalNav li a').click
            showSection( $(this).attr('href') );
        });
        //});
        if(window.location.hash) // If hash found then load the tab from Hash id
        {
           showSection( window.location.hash); // To get the div id
        }
        else // If no hash found then default first tab is opened
        {
            $('ul#verticalNav li:first-child a').click();
        }
    }
});

HTML source code

<ul>
    <li><a href="#a">a</a></li>
    <li><a href="#b">b</a></li>          
    </ul>
    <div id="sections">
    <div class="section" id="a">
    </div>
    <div class="section" id="b">
    </div>

Answer №1

Insert

$('body').scrollToTop(0);

inside the click event.

Answer №2

@dollarvar 's response may not be flawless.

$('html').scrollTop(0); -- exclusive to IE
$('body').scrollTop(0); -- for all browsers except IE
$('body,html').scrollTop(0); -- compatible with all browsers

I conducted a brief demonstration. Here is the sample code provided:

HTML:

<div style="height:400px; line-height:400px; background-color: gray; text-align:center; color:white; margin:20px;">Empty space for testing</div>
<ul id="verticalNav">
    <li><a href="#a">a</a></li>
    <li><a href="#b">b</a></li>
</ul>
<div id="sections">
    <div class="section" id="a">Content A. Content A. Content A. Content A. Content A. </div>
    <div class="section" id="b" style="display: none;">Content B. Content B. Content B. Content B. Content B. </div>
</div>
<div  style="height:800px; line-height:800px; background-color: gray; text-align:center; color:white; margin:20px;">Empty space for testing</div>

JQuery:

<script type="text/javascript">
$(document).ready(function(){
    $("#verticalNav a").click(function(){
        // toggles visibility of content sections
        $($(this).attr("href")).show().siblings().hide();

        // scrolls to the position of #verticalNav
        $('body,html').animate({
            scrollTop: $("#verticalNav").offset().top
        }, "slow");

        return false;
    });
});
</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

How can PHP be used to compare a value with an array and assign it to a variable?

Hello, I have an HTML form that includes a select element. The options in this select element do not display the actual value to prevent SQL injections. Here is the HTML form: <select type="text" name="code"> <option value="1"> ...

"Troubleshooting: NuxtJs vue-flip feature stuck on front side, not rotating to

I have recently installed the vue-flip plugin in a NuxtJs (VueJS) project that I created using the command: npx create-nuxt-app <project-name>. In the index.vue file, I simply added: <vue-flip active-click="true"> <div slot="front"> ...

What is the best method for executing an application on the client side using Node.js?

Is it possible to initiate communication with an external program from the client side? Imagine I have a Node.js server paired with AngularJS or another framework. I want users to be able to click a button on the browser, causing a pre-installed client-si ...

Accessing Json Data Using AngularJS User Authentication

Currently, I am in the process of developing a user login page that stores user information in a json file. I have successfully created the GET method for accessing the file, but I am facing difficulty in redirecting the user after a successful login. Any ...

The process of making a pop-up modal instead of just relying on alerts

Attempting to change from using an alert to a pop-up with a simple if statement, but encountering some issues. Here is the current code: if(values == ''){ $('body').css('cursor','auto'); alert("Blah Blah..." ...

Using ajax to load a bootstrap button with a loading feature

I am currently working on a project where I need to delete a record from MySQL using AJAX. Everything is functioning correctly, but I would also like to incorporate a loading feature for the button when the trash icon is clicked. The button link can be fou ...

The issue arises when trying to retrieve values through AJAX to populate input fields using jQuery, but for some reason

When sending data to check whether an item exists or not, I return 1 if it does, and 0 otherwise. I am using the CodeIgniter framework for a jQuery Ajax request, but after the values are returned in Ajax, I am unable to retrieve them directly upon completi ...

Django informing me that the template is not found

Why am I getting a "template does not exist" error in Django? I'm trying to navigate from film_detail.html to film_report.html by clicking on the "report" button... views.py class FilmReport(LoginRequiredMixin, UpdateView): model = Report fi ...

Submitting data from two Vuejs components: A guide

I have a scenario where I need to submit data from two different forms (form1 and form2) to the server in a single request when the Save button is clicked. How can I achieve this? Thanks for any help! Here is the code I currently have: <template> ...

Challenge with line breaking and shortening lengthy content in Angular

Struggling with properly wrapping and truncating long text in an Angular project. The goal is to wrap the text in 2 lines and if it goes beyond that, add "..." at the end of the second line. Pure CSS doesn't work because the text needs to be left-alig ...

Exploring the power of indexing in @for loop within HTML in Angular 18

Is it possible to define the index variable in @for loop in Angular 17? const users = [ { id: 1, name: 'Ali' }, { id: 2, name: 'reza' }, { id: 3, name: 'jack' }, ]; <ul> @for (user of users; track user.i ...

Switch between different react components

When a component is opened, I want all other components to close. Whenever they are clicked, they will display a list. class ParentComponent extends Component{ constructor(props){ super(props) this.state= {...} } render(){ return( ...

Problem with Angular Slider

I'm in the process of creating a carousel component in Angular, but I'm facing an issue where the carousel is not appearing as it should. Below is the code for my carousel component. carousel.component.html: <div class="carousel"> ...

What is the best way to position a container div over another container using Bootstrap or CSS?

https://i.sstatic.net/q1qGi.png I'm working on a Bootstrap 4 layout where container B needs to overlay part of container A. I want to achieve a design where container B appears on top of container A. Any suggestions or references on how to achieve th ...

Error Handling with Node.js Sequelize RangeError

Currently, I am in the process of setting up a table to store user sessions. Specifically, I plan to save the IP address as an integer and have been exploring various methods for achieving this. You can find more information on this topic here: IP-addresse ...

How come the hover feature in VS Code doesn't display the "null" part of my JSDoc type definition union?

Here is an example of a LinkedList class definition that utilizes JSDoc and jsconfig.json for type checking in VSCode. The issue lies in displaying the type of value and next as union types with undefined, which is not currently happening. class LinkedList ...

What is the process for incorporating the input type="number" into a Laravel Blade template?

Is there a way to create an input field for users to enter only numbers in blade? In HTML5, we can use <input type="number">. How can this be achieved in blade? I attempted the following: {!! Form::number('amount', null, array('class ...

Designing a platform for dynamic components in react-native - the ultimate wrapper for all elements

export interface IWEProps { accessibilityLabel: string; onPress?: ((status: string | undefined) => void) | undefined; localePrefix: string; children: JSX.Element[]; style: IWEStyle; type?: string; } class WrappingElement extends React.Pure ...

Identify the significance within an array and employ the filter function to conceal the selected elements

I'm in the process of filtering a list of results. To do this, I have set up a ul list to display the results and checkboxes for selecting filter options. Each item in the ul list has associated data attributes. When a checkbox with value="4711" is c ...

When clicking on an HTML link pointing to a cloud, it does not open in the same frame but instead opens in a new window

I am currently working on an HTML5 application that features a screen divided into two parts. The left part of the screen contains a few links, and upon clicking one of these links, the resulting content should open in the right side frame within the same ...