Adjust the scrollTop of the tab-content when navigating between different tabs

When I scroll through the content of menu1 and then click on the menu2 tab, the content for the menu2 tab is displayed. However, I am facing an issue with changing the scroll position of the tab content so that it is visible from the top.

I attempted to use javascript, but encountered a specific problem.

.nav-tabs{
  background:#f1f1f1;
  position: sticky;
  top: 56px;
  z-index:9999;
}
body{
  width:400px;
  height:300px;
  overflow:scroll;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<body>

<div class="container">
  <h2>Dynamic Tabs</h2>

  <ul class="nav nav-tabs">
    <li class="active"><a data-toggle="tab" href="#menu1">Menu 1</a></li>
    <li><a data-toggle="tab" href="#menu2">Menu 2</a></li>
  </ul>

  <div class="tab-content">
    <div id="menu1" class="tab-pane fade in active">
      <h3>Menu 1</h3>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
      Curabitur fringilla ex ut lorem molestie, quis hendrerit neque consequat.
      Donec et enim vitae purus condimentum pretium ac vel ante.
      Quisque posuere arcu nec mi aliquam tincidunt.
      Nullam blandit ultricies est ac vulputate.
      Nam non risus non nunc fermentum bibendum eget vel sem.Sed semper magna urna.
      Fusce iaculis justo metus, a viverra tortor facilisis at.
      Nullam ornare volutpat nisl, sed cursus libero dapibus eu.
      Integer mollis metus sed justo consectetur, non laoreet odio convallis.
      Sed lobortis velit lacus, vel bibendum dui eleifend sit amet.
      Morbi pulvinar nunc lacus, sollicitudin accumsan sapien imperdiet eu.
      Aenean luctus nisi a orci tempus suscipit.Quisque pharetra sagittis mattis.Suspendisse potenti.
      Etiam dignissim efficitur ligula, at dictum orci vestibulum rhoncus.
      Proin faucibus felis massa, eu malesuada erat commodo ac.
      Cras congue tellus augue, a vehicula turpis tristique in.Duis sodales mauris diam!
      Ut pellentesque eros non maximus elementum.Mauris finibus porttitor rutrum?
     </p>
    </div>
    <div id="menu2" class="tab-pane fade">
      <h3>Menu 2</h3>
      <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque

     </p>
    </div>
  </div>
</div>

</body>

Answer №1

To ensure the page scrolls to the top when a menu item is clicked, simply assign a class to each menu item, such as menu-item, and then employ jQuery's scrollTop(0) function on any menu item click event using the following snippet:

$(".menu-item").click(function() {
    $("html, body").scrollTop(0);
});

For a demonstration of this in action with your own code, check out: https://jsfiddle.net/Matthew_/L8hdbx7v/10/

If you prefer not to rely on jQuery, an alternative approach is to use:

window.scrollTo(x-value, y-value);

Answer №2

Creating this with JavaScript is a breeze.

Check out this example I put together and let me know what you think:

$(window).scroll(function(e){
 var tabs = $(".nav-tabs");
 var height = $(window).scrollTop();
 var pos =tabs[0].getBoundingClientRect(); 
 if (pos.top + pos.height < height)
     tabs.css({ top:0, position: "sticky" }); // make it sticky 
  else tabs.attr("style", ""); // reset to default
});
   // when changing the menu scroll to top. 
$(".nav-tabs li").click(function() {
 window.scrollTo(0,0);
 var pos= $(".nav-tabs")[0].getBoundingClientRect(); 
 window.scrollTo(0, (pos.top + pos.height))
   });
.nav-tabs{
  background:#f1f1f1;
  top: 56px;
  z-index:9999;
}
body{
  width:400px;
  height:300px;
  overflow:scroll;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<body>

<div class="container">
  <h2>Dynamic Tabs</h2>

  <ul class="nav nav-tabs">
    <li class="active"><a data-toggle="tab" href="#menu1">Menu 1</a></li>
    <li><a data-toggle="tab" href="#menu2">Menu 2</a></li>
  </ul>

  <div class="tab-content">
    <div id="menu1" class="tab-pane fade in active">
      <h3>Menu 1</h3>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris euismod leo at nisi tempor, nec volutpat lacus ultricies.
      Nam tristique urna mauris, id tempus turpis feugiat vel. Curabitur at finibus mi. Etiam nec neque velit.
      Suspendisse potenti. Proin ut quam faucibus, sollicitudin nisl sed, tincidunt sem. Pellentesque nec orci vitae justo fringilla aliquet imperdiet ac nulla.
      Fusce vehicula massa est, eget scelerisque ex efficitur quis. Quisque non purus hendrerit, vestibulum augue at, placerat orci.</p>
    </div>
    <div id="menu2" class="tab-pane fade">
      <h3>Menu 2</h3>
      <p>Vivamus pretium metus ligula, sit amet fermentum eros rutrum et. Phasellus varius dignissim libero,
      id mollis tortor commodo ac. Integer interdum diam eleifend sapien rhoncus suscipit. Ut vulputate blandit dapibus.
      Duis vitae elementum enim. In hac habitasse platea dictumst. Sed sit amet lectus ante. Fusce faucibus sodales ipsum nec pellentesque.
      Donec auctor nibh quis diam malesuada, at viverra nunc cursus. Aenean convallis maximus odio in condimentum.
      Curabitur bibendum magna facilisis, accumsan augue at, congue lorem. Vestibulum pharetra pulvinar neque, ac venenatis velit convallis gravida. Nullam dictum mattis consequat.
      Maecenas sagittis dui ut vestibulum gravida. Mauris nec eros fermentum, hendrerit dolor molestie, egestas nisi.
      Nam in felis run ut[/KEYWORD]&, dictum risus arcu. Aliquam quis varius turpis.</p>
    </div>
  </div>
</div>

</body>

Answer №3

If I had to choose, I would adjust the scrollTop property of either:

  1. the tab-content element
  2. the window content

Since the menu-item is part of (and likely set to display: block) the parent element, setting scrolltop on this element may not achieve the desired effect.

In plain JavaScript, you can use element.scrollTop = value; https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop

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

Transmitting chosen option using AJAX and JavaScript

I have a select dropdown that I want to use to send a selected option to AJAX and then display it. Here is my HTML: <label>Tag</label> <select id="day"></select> <label>Monat</label> <select id="month"&g ...

When printing a PDF, a div that is set to 100vh only takes up

After setting the div to be 100vh, I realized that when printing it only takes up half of the page. Adding media print did not make a difference, and even trying to set the height to 100% instead didn't work for PDFs. html, body { height: 100%; ...

Creating a recursive function in JavaScript to build a menu list object

Having an assortment of ['/social/swipes/women', '/social/swipes/men', '/upgrade/premium']; The objective is to create a map object that mirrors this structure: { 'social': { swipes: { wom ...

The image begins rotating only after the second click has been made

Having trouble with jQuery and rotation effects on an image? I have a solution for you. The image should rotate while toggling at the same time, but there's a twist - on the first click, it won't rotate but will still toggle. From the second clic ...

Enable the use of multiple decimal separators in a ReactJS application

I am currently developing a small project that involves using a POST request, which requires multiple fields with 2 float values. My backend system expects the decimal separator to be a ".", but my target audience is primarily French and they ar ...

I am puzzled by this error in Typescript: "Why does the element have an 'any' type when the Object type lacks an index signature?"

Looking to extract an array of keys from an object with nested properties, my current code: public static getKeys(obj: Object) { let keys: string[] = []; for (let k in obj) { if (typeof obj[k] == "Object" && obj[k] !== null) { ...

I wonder about the origin of this variable

I found this example in a textbook. My confusion lies in the origin of this interval variable. Where does it come from? It's not defined within the data block, and you can't simply create a variable by assigning a value to it. Could it possibl ...

Transforming JSON into a specialized text structure

After receiving JSON data from the server, I am required to convert it into a different format as shown below: {"1":"82700","2":"26480","3":"31530","4":"22820","5":"15550","6":"205790"} Although I have attempted to achieve this with the provided code sni ...

Localizing strings that are not saved in a database

Our web app will soon support multiple languages, a new feature we are excited to roll out! Currently, we utilize Handlebars for front-end templating and Node + Jade for back-end templating. As we prepare to implement language support, we're conside ...

Achieve SEO excellence with Angular 4 in production settings

I am currently building a website using Angular 4 as part of my personal study project. Although my website is live, I realized that it's not SEO friendly. After making some changes, I came across a valuable resource on server-side rendering in Angul ...

Beginner guides on creating combo boxes and Facebook-style message composers using CSS and Javascript (or JQuery)

1) Looking to revamp a combo box using CSS and minimal or no javascript. Seeking tutorials that can provide guidance. 2) Facebook users may have noticed the feature where typing in recipients creates a "button" around the user's name. Curious about h ...

How to Implement Infinite Scrolling in Ionic Framework Using HTTP Requests

Recently, I started using the amazing ionic framework and I am new to angular. I have a web service up and running, and my app is supposed to load data. I have succeeded in retrieving data, however, the WordPress rest API sends data in the form of pages. I ...

Is there a way to horizontally center Material UI Switch and its icon props?

I'm using Material-UI to implement a Switch component on my project. This particular component allows for the addition of icons, however, I've encountered an issue with alignment when including them. Is there a way to horizontally center align b ...

Break apart animation similar to the 🎊 emoji using CSS styling

I am attempting to create an animation of a circle splitting open on two sides, similar to the ...

Tips for effectively utilizing vue-draggable (or Sortable JS) within a v-data-table using the powerful combination of Vuetify 2 and Vue JS 2

I'm currently experimenting with integrating vue-draggable into Vuetify's v-data-table based on the instructions provided in this article : https://medium.com/vuetify/drag-n-drop-in-vuetify-part-ii-2b07b4b27684 The article mentions : "The main o ...

Update the contents of a neighbor div within the same parent element using jQuery

Attempting to set the range slider value within the slider parent sibling var updateRangeSlider = function() { var slider = $('.range-slider'), range = $('.range- value = $('.range-slider__value'); sli ...

The ideal login page design

I apologize for my lack of knowledge in React, but I am quite new to it and have been struggling with this issue for days. I am having trouble creating a login page in ReactJS. Here is the code in my app.js: import React from 'react'; import {Ha ...

Accessing node postgres and fetching combined fields with duplicate names

Currently, I am developing a node.js application that utilizes the pg package to connect to a PostgreSQL database. The problem I am encountering involves querying data using a join statement and finding that fields from one table overwrite those from anoth ...

Using JavaScript to organize and categorize data within an array

I am working with a multidimensional array and need to filter it based on the value at a specific index position. Here is what the array looks like: arr = [ [1 , 101 , 'New post ', 0], [2, 101 , 'New Post' , 1], ...

Managing the size of personalized shapes in Three.js

I need help with a custom object that represents a frame created by subtracting two meshes. generateFrame (width, height, depth) { const frameMesh = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1)); frameMesh.scale.set(width, height, depth); c ...