m3div0
m3div0

Reputation: 1596

Enable div to scroll by keyboard without clicking

I have div element in which I am loading text, usually long text, so the div has scrollbars. I can scroll in this div with mouse, when the cursor is on it, but I cant scroll with page up and down, unless I click inside the div first. So Is there a way to avoid this clicking, to do it from code when the text is loaded?

Upvotes: 7

Views: 8031

Answers (2)

dvanrensburg
dvanrensburg

Reputation: 1441

The answer here worked for me:

Set keyboard focus to a <div>

Basically add a tabindex to the div:

<div id="mydiv" tabindex="-1">

then programmatically set the focus using: document.getElementById("mydiv").focus();

From the original post:

The tabindex value can allow for some interesting behaviour.

  • If given a value of "-1", the element can't be tabbed to but focus can be given to the element programmatically (using element.focus()).
  • If given a value of 0, the element can be focused via the keyboard and falls into the tabbing flow of the document.
  • Values greater than 0 create a priority level with 1 being the most important.

Upvotes: 4

Todd
Todd

Reputation: 5454

Here it is, as you described. I appended an input to the content div, then focus() it, rather than trying to focus the div. So, immediately after pressing load text, you can press pg up/dn to scroll div.

HERE IT IS

 $("div").append('<input type="text" id="focusDiv">');
    /*
 Here I need to have some code which gives "focus to the div, so if I press the load text and then immediately PageDown key, sthedvis scrolls down.

 $("button").on("click", function (e) {
    e.preventDefault();
    $("div").html("Very long text...");
    $("div").append('<input type="text" id="focusDiv">');
    $('#focusDiv').focus();
});

Upvotes: 1

Related Questions