6

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?

m3div0
  • 1,556
  • 3
  • 17
  • 32
  • can you add sample code, like with jsfiddle, to illustrate? i'd like to help, but i'm unclear on your exact issue. – Todd Mar 27 '13 at 10:45
  • Yep I can, hope it'll help a bit http://jsfiddle.net/BQQ8C/1/ – m3div0 Mar 27 '13 at 15:15

2 Answers2

2

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.
Community
  • 1
  • 1
dvanrensburg
  • 1,351
  • 1
  • 14
  • 21
1

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();
});
Todd
  • 5,314
  • 3
  • 28
  • 45
  • I was trying to find some more valid solution, but this isn't so bad and works great, thanks! – m3div0 Mar 27 '13 at 18:16