Avoid having the browser automatically move focused elements that are navigated to using the tab key

When moving through form elements or anchors using the tab key (and shift + tab), the browser automatically scrolls to the focused element. If the element is not visible due to being part of overflow content with a hidden overflow setting, the container's content is shifted to reveal the focused element. I am looking for a way to disable or counteract this behavior.

Here is an example demonstrating the issue in Chrome:

https://jsfiddle.net/charlieko/wLy7vurj/2/

var container = $("#container")
var cur = 0;

function go(increment) {
  var next = cur + increment;
  if (next < 0) next = 4;
  else if (next > 4) next = 0;
  cur = next
  var newX = cur * 500;
  container.css({
    transform: 'translate(-' + newX + 'px, 0)'
  })
}

$("#left").click(function(e) {
  go(-1);
});
$("#right").click(function(e) {
  go(1);
});
body {
  overflow: hidden;
}
#container {
  width: 2600px;
  overflow: none;
  transition: transform 0.4s;
  transform: translate(0, 0);
  overflow: hidden;
  margin: 0;
}
li {
  width: 500px;
  text-align: center;
  list-style-type: none;
  float: left;
  margin: 0;
  padding: 0;
}
a {
  color: black;
  font-size: 2.0rem;
}
#ui {
  position: fixed;
  top: 200px;
}
#ui span {
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <ul>
    <li><a href="#">Link 1</a> | ABCD EFG</li>
    <li><a href="#">Link 2</a> | HIJK LMNO</li>
    <li><a href="#">Link 3</a> | PQRSTU VW</li>
    <li><a href="#">Link 4</a> | XYZA BC</li>
    <li><a href="#">Link 5</a> | DEFG HI</li>
  </ul>
</div>
<div id="ui">
  <div>
    <span id="left">Left</span>
    |
    <span id="right">Right</span>
  </div>
  <p>
    Use left and right to move. Issue: Use tab key (and shift+tab) to navigate to any of the links. The container of the links shift to show the focused link. Notice the content is decentered when it happens.
  </p>
</div>

The problem now is that there are two ways to slide the contents: by interacting with the left/right buttons and by using the tab navigation. When navigating tabs, it disrupts the sliding logic as the content becomes off-center and the saved index no longer matches what's on the screen. I can address the accessibility issue programmatically with an onFocus event, so this automatic scrolling isn't necessary.

Is there a method to disable this behavior? I have already attempted using the preventDefault() method on the onFocus events of the anchor elements.

Answer №1

After some investigation, I managed to discover a solution. It turns out that the browser automatically scrolls the immediate parent of any overflowing content in order to position the focused element at the center. By simply adjusting the scrollLeft property of the parent element, the issue was resolved. Therefore, within the onFocus event for the link:

function onFocus (e) {
    document.getElementById('content-parent').scrollLeft = 0;
    // Additional code for repositioning the actual content using transform with transition animation
}

Answer №2

Using overflow:hidden is a common practice for content that needs to scroll and move, making it challenging to prevent this behavior. If you want the Tab control to only be visible on elements that are within the viewport (including buttons or links that update your slider), you'll need a different approach to hide your content instead of relying solely on overflow.

Consider using display:none for your list items until they become visible within the open part of div#container. This technique removes them from the DOM and eliminates keyboard focus until they are needed. By creating a 'hidden' class with display:none properties, you can easily add or remove the class from list items when Left/Right controls are activated. Unfortunately, I cannot provide a code sample at the moment due to limited screen space.

An issue may arise where keyboard users cannot access the Left/Right controls. To address this, change these controls to button or link elements so they have default keyboard support in all browsers. This way, all users, whether using a mouse or keyboard, can rely on the Left/Right controls for navigation, giving you more control over the user experience.

Answer №3

To prevent links from being focused, consider setting the tabindex attribute to -1.

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

Definition of a Typescript Global.d.ts module for a function that is nested within another function

Simply put, I have a npm module that exports a function along with another function attached to it: // @mycompany/module ... const someTool = (options) => { // do some cool stuff }; someTool.canUseFeature1 = () => { return canUseSomeFeature1(); ...

Tips for securely storing visitor-entered form data on our computer from our webpage

Is there a way to store the information filled out by visitors on our website? <ul class="form"> <li class="short"> <label>First Name<span class="required"></span></ ...

The issue of incorrect encoding in JavaScript Blob while retrieving a file from the server

Implementing a FileStreamResult from C# in a SPA website (using .NET Core 2, SPA React template), I make a request to fetch a file from my endpoint. This triggers the following response in C#: var file = await _docService.GetFileAsync(token.UserName, inst ...

Deciphering HTML encoding for text fields

As I transition from the Microsoft stack, specifically WPF, to HTML5, I apologize for any beginner-level questions. Today's topic is HTML encoding and decoding. Imagine an HTML5 application making AJAX calls to a C# backend using HTTP. The server al ...

Creating a 404 Error Response in Express.js

Inside app.js, I currently have the following code: // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); This code executes when a non-existent URL ...

Why do I receive the error message "Error: Objects are not valid as a React child (found: [object Promise])" in NextJS13?

I'm feeling overwhelmed by this issue and unsure of how to resolve it. Here is the code that is causing trouble: 'use client' import React, { useState } from 'react' import AnimatedDiv from '../../../(shop)/(components)/animat ...

Combining multiple events into one function using jQuery

I am searching for the opposite of what everyone else is seeking. I have an anonymous jQuery function that I want to keep as it is, but I need to attach multiple event handlers to it on different occasions (specifically two events). When the text inside ...

Does the content from an AJAX request get loaded if you flush it using ob_flush()?

Imagine this scenario, where we are making an AJAX request and inserting the result inside a div with the id of "result". On the backend, the script is using ob_flush() to send the header but not terminating the request until it's explicitly terminat ...

What distinguishes event-stream.through from event-stream.map?

After reviewing the documentation on event-stream, it appears that the main distinction between these two methods is whether they operate synchronously or asynchronously. However, I am still unclear on the true significance of this difference. ...

Internet Explorer does not automatically resend AJAX requests after submitting a form

Specifically mentioning IE in my title because my code functions correctly on Chrome. The "Maintenance" view I have is responsible for creating, editing, and deleting. The form is located in a partial view named "_MaintenanceForm" with its own GET/POST met ...

Add a Variety of Data Entries to a Table

I am currently attempting to add multiple pieces of data (from a date form) into a table using Jquery and MomentJS. However, the output does not appear as desired. Below is my code: $(".btnNext").on('click', function(e) { var Day = 1; ...

Guide on utilizing every array value during each iteration of a for loop, ensuring that the same number of values

Below is the equipos_seleccionados array: ["12 - v4", "100 - v500"] This is a preview of the frontend: https://i.sstatic.net/nJU9d.png When you input values in the head section, textboxes are generated automatically. Objective: Assi ...

"Encountering issues with Rails and AJAX where the data returning is showing up

I am facing a challenge while trying to use AJAX in Rails to POST a comment without using remote: true. I am confused as to why my myJSON variable is showing up as undefined, while data is returning as expected. Check out my code below: function submitVi ...

Transferring Data between Rails and Angularjs using JSON

Utilizing Angularjs to fetch JSON data from a Rails test app deployed on Heroku is proving to be a bit challenging. Below you can find the snippets of my Angular and Rails code. An error message displayed in my Firebug console reads: "NetworkError: 404 N ...

Creating an interactive date selection feature with a calendar icon in MVC 5

I currently have a textbox that displays the datepicker when clicked. However, there is now a requirement to add a calendar icon inside the textbox. The datepicker should be displayed when either the calendar icon or the textbox is clicked. Below is the co ...

What is the correct way to establish an array variable containing objects?

What is the correct way to declare an object within an array variable? I encountered the following error message: "TypeError: Cannot set property 'name' of undefined" Here is the code snippet in question: let data = [] data[0].name = "john" ...

Searching for an object within an array in NodeJS that is not present in another array

One of my challenges involves working with two arrays of objects: var existingUsers1 = []; existingUsers1.push({ "userName": "A", "departmentId": "1" }); existingUsers1.push({ "userName": "B", "departmentId": "1 ...

How can a button be linked directly to a particular list item?

I currently have a HTML tag within my React application that looks something like this: <ul> <li> Item 1 <button> Delete </button> </li> <li> Item 2 <button> ...

"Which is better for maximizing the efficiency of an image grid: CSS or Jquery? What are the key

As a UX Designer looking to enhance my coding skills, I must admit my code may not be perfect. Please bear with me as I navigate through this process. I am in the process of revamping my portfolio website. The original seamless grid was created using a Ma ...

Using NextJs <Script> is only effective after a page has been reloaded

Currently delving into the world of NextJS and encountering an issue with integrating a third-party ebay script onto one of my route pages. The script only seems to appear sporadically upon reloading the page. However, when navigating to the store page via ...