Scroll the table automatically when the currently selected row is the second-to-last row

Having trouble with a scrolling table issue. https://i.sstatic.net/PFyN3.png

Upon page load, the first row (ROW 1) is automatically selected and highlighted. Clicking the next button selects and highlights the subsequent rows. However, once ROW >= 8 (e.g. ROW 9, 10...etc.) are selected, the table fails to scroll automatically, causing the currently selected row to be out of view even though it's highlighted. Expected behavior can be seen in this image: https://i.sstatic.net/xtTyL.png

When ROW 8 is selected, automatic scrolling should kick in. This ensures that the next row (ROW 9) stays visible while the previous rows remain hidden.

The goal is to always have the currently selected row and the next row visible at the same time when navigating using the next/previous buttons. The table should continue to scroll until reaching the last visible row and then shift to show the row before it.

I'm stuck on how to fix this issue. Any assistance would be greatly appreciated.

Best Regards, Ken.

Answer №1

In the following code snippet, the use of the window object is demonstrated to scroll to a specific tr element within a table.

When the next/prev buttons are clicked, the selectedIndex value is incremented/decremented accordingly and the page scrolls to that particular row in the table.

var app = angular.module("app", []);

app.controller("ctrl", function($scope) {
  $scope.selectedIndex = 0;
  $scope.rows = ["Row1", "Row2", "Row3", "Row4", "Row5", "Row6", "Row7", "Row8", "Row9", "Row10", "Row11", "Row12", "Row13", "Row14", "Row15", "Row16", "Row17", "Row18"];

  $scope.NextRow = function() {
    $scope.selectedIndex = $scope.selectedIndex === $scope.rows.length - 1 ? $scope.rows.length - 1 : $scope.selectedIndex + 1;
    var w = $(window);
    var row = $('table').find('tr').eq($scope.selectedIndex);
    if (row.length) {
      w.scrollTop(row.offset().top - (w.height() / 2));
    }
  }

  $scope.PrevRow = function() {
    $scope.selectedIndex = $scope.selectedIndex === 0 ? 0 : $scope.selectedIndex - 1;;
    var w = $(window);
    var row = $('table').find('tr').eq($scope.selectedIndex);

    if (row.length) {
      w.scrollTop(row.offset().top - (w.height() / 2));
    }
  }
});
body {
  padding-top: 50px;
}

.anchor {
  border: 2px dashed DarkOrchid;
  padding: 5px 5px 5px 5px;
}

.fixed-header {
  background-color: rgba(0, 0, 0, 0.2);
  height: 50px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
}

.fixed-header>a {
  display: inline-block;
  margin: 5px 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="app" ng-controller="ctrl">

  <div class="fixed-header">
    <button ng-click="PrevRow()">Previous button </button>
    <button href="" ng-click="NextRow()">Next button </button>
  </div>

  <div>
    <table>
      <tbody>
        <tr ng-repeat="row in rows">
          <td class="anchor" ng-style="selectedIndex == $index && {'background-color':'lightblue'}">{{row}}</td>
        </tr>
      </tbody>
    </table>
  </div>

</body>

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

Troubleshooting jQuery window scrolling and detecting element positions issue

I am utilizing the $(window).scroll(function() method to dynamically change classes on the navigation menu as different sections come into view on a website. Whenever a section becomes visible, the navigation class is updated to 'current'. $(win ...

Struggles with Managing 5-Digit Unicode Characters with jQuery

I need some assistance with using larger Unicode images in JQuery, as I am encountering difficulties that I cannot seem to resolve. For example, when I use the following line of code: if ( IsItOverFlowing() ) { $HM.text("\u2302"); } a charming litt ...

Focus on a specific div element while bypassing its parent

Can I directly target the element with .div-3 class, even if its parent does not have an id or class? <div class="wrapper"> <div> <div> <div class="div-3"> </div> </div> </div> </div> I am aware ...

In terms of function efficiency, what yields better results: using conditional execution or employing conditional exit?

Feedback is welcomed on the efficiency of the following JavaScript/TypeScript solutions: function whatever(param) { if (param === x) { doStuff(); } } or function whatever(param) { if (param !== x) { return false; } doStuff(); } The se ...

Another method to verify an input using HTML5 regex and JavaScript

When working with vanilla JavaScript to check an HTML input against a regex pattern, things can get tricky. I find myself going back to the parent element to validate the input, and while it works, it's not as elegant as I would like it to be. Here i ...

Learn how to easily alter the background color of a div in real-time by utilizing a color picker or color swatches feature in your

Would it be feasible to dynamically alter the background color of the .hasPicked class? I am interested in adjusting the background color using an input color picker and color swatches. I have already included the necessary code on Codepen. Check it out h ...

Using a uibCollapse within a nested directive element may not function as expected

Whenever I try to click on my custom directive, the elements that are supposed to expand remain collapsed. To ensure that the click event is actually triggered, I have specified a size in the css for the .btn class. // index.html <body ng-controller=" ...

Transforming seconds into years, months, weeks, days, hours, minutes, and seconds

Can anyone help me modify Andris’ solution from this post: Convert seconds to days, hours, minutes and seconds to also include years, months, and weeks? I am currently running this code: getDateStrings() { console.log(req_creation_date); const toda ...

JavaScript unable to access elements during page loading

I am facing an issue with the following code: var coll = document.getElementsByClassName("collapsible"); var i; for (i = 0; i < coll.length; i++) { coll[i].addEventListener("click", function() { this.classList.toggle("active"); v ...

How can I transform a JSON object into a series of nested form fields?

Can anyone suggest a reliable method for converting a JSON object to nested form fields? Let's consider the following JSON object: {'a':{'b':{'c':'1200'}}}, 'z':'foo', 'bar':{&apo ...

Exploring Non Blocking IO through an Example

While browsing through a node.js tutorial, I stumbled upon this informative page that uses the example of a "Restaurant service" to explain a scenario. In the context of Blocking IO, they provide the following code snippet: // requesting drinks for table ...

how to bind data to an array in Angular

I recently developed an Angular 7 application that features the capability to dynamically add and remove controls. However, I am facing challenges when it comes to binding the data to the form. In the code snippet below, I am focusing on the process of ad ...

What is the method for determining the data type of a column in an Excel sheet that has been

Currently, I am utilizing the XLSX npm library to convert an Excel sheet into JSON format. However, all of the retrieved data is currently being returned as strings. To see a demo of the XLSX read process, you can visit this Stackblitz demo Is there a w ...

Setting the height of the text area in a three-column layout cannot be achieved using a percentage value

I'm working on creating a 3-column layout with two text areas. The issue I'm facing is that when I adjust the width of the text areas to create columns, the height shrinks. I need a solution that will be compatible with HTML5 browsers - support f ...

What is the best method to activate or deactivate a link with jQuery?

Can you provide guidance on how to toggle the activation of an anchor element using jQuery? ...

The jQuery UI Tab is failing to scroll within its container

Scenario : I am facing an issue with a scrollable container in IE8. The containing div is supposed to be scrollable and it holds my jquery UI tab div. Issue: While scrolling the container in IE8, other content within it also scrolls, but the jQuery UI t ...

Eliminate the ending slash from your Nuxt application

Hello, I am currently working on a Nuxt Application and encountering an issue. After running the npm run build command and starting it with npm start, there seems to be an inconsistency with trailing slashes. During the build, the URL appears without a t ...

How can I extract data from the 'ngx-quill' editor when integrating it with a FormBuilder in Angular?

After implementing the 'ngx-quill' editor package in my Angular 15 project, I encountered an issue where the value of the content form control was returning 'null' upon form submission using FormBuilder. Despite entering text such as he ...

Enhance your cloud functions by updating data

Recently, I encountered an issue with a function I wrote that interacts with the Real Time Database. Every time I attempted to write data to a specific node, it would add the complete dataset and then promptly delete everything except one entry. https://i ...

Mastering Yii2: Implementing Javascript Functions such as onchange() in a View

One of the elements in my project is a checkbox: <div class="checkbox"> <label> <?= Html::checkbox('chocolate', false) ?> Chocolate </label> </div> In addition to that, I also have a span ta ...