Home and End keys don't work when popup created on page?

html, javascript, jquery

Solution

`focus()` won't actually give keyboard focus to an element unless the element is focusable. Interactive elements like `input` and `textarea` are focusable, but by default a `div` is not. However, you can make it focusable by setting its `tabIndex` property (or `tabindex` attribute).

When I load your page and type the following into console:

$(".productPopupContainer").prop("tabIndex", "-1");
$(".productPopupContainer").focus();

The Home and End keys begin to work even though I haven't clicked in the popup. (I'm using the latest version of Chrome on a Mac, btw).

The jQuery documentation page for focus() has a good explanation of how this works.

FUN FACT: If you don't set `tabIndex` on an element but read that property, you'll get -1:

var elem = document.getElementById("#anything");
console.log(elem.tabIndex); // prints -1

But internally in the browser, the value is actually not defined, because explicitly setting it to -1 makes it focusable, when it wasn't previously. This means you can actually do this to make an element focusable without affecting its tab order:

elem.tabIndex = elem.tabIndex;

Problem

If you take a look at this page you'll see a bunch of products in containers. If you click on one of the products, a popup will open that will (most likely) have a greater height than the browser window and so a scrollbar will be shown. After a popup is opened, the Home and End keys do not make the element scroll when pressed. However, if you click in the popup, then the keys work. I've tried calling `.focus()` and `.click()` on the popup after opening it, but the Home and End keys still don't have any effect until I click in the popup with my mouse. Why don't the Home and End keys make the element scroll when pressed, and how can I get them to work?

Original source