1

Im trying to get focus to hidden div that shows up after the .show() function is called on it. Iv tried a couple things including show().focus() or splitting it up into

$(".messageDisplayArea").show();
$("#message_display_area").focus();

the div shows up, but the page does not shift focus to it.

<script>
    function showMessage(id, row) {
            selectRow(row);         
            $(".messageDisplayArea").show();        
            $("#message_display_area").focus();
    }

</script>


<div class="messageDisplayArea" id="message_display_area" style="display: none;">

<p> Test Test Test </p>

</div>

what am I missing? the page that this is in is decently large and the div appears at the bottom of the page. I want the browser to jump down and put the new div in focus

CoffeePeddlerIntern
  • 575
  • 3
  • 9
  • 27
  • what do you mean by wanting to put a focus in a `div` element? – Sergio Jul 08 '13 at 16:24
  • maybe i am misunderstanding the .focus() function. What i want to do is give literal focus to this new div that appears. As in have the browser jump to the div since it appears at the bottom of the screen and the user doesnt even know its there until they scroll down – CoffeePeddlerIntern Jul 08 '13 at 16:27

4 Answers4

2

Replace this line:

$("#message_display_area").focus();

with this line:

window.location.hash = "message_display_area";
Kevin Boucher
  • 14,990
  • 3
  • 40
  • 54
2

As far as you've given us code, what you have should work, as in this fiddle.

http://jsfiddle.net/SuERE/

http://jsfiddle.net/SuERE/1/

HTML:

<button type="button">Show and Focus</button>
<div style='height:700px'></div>
<input type="text" id="input" style='display:none;'/>

Javascript:

$("button").on("click",function(){
   $("#input").show();
    $("#input").focus();
});
Samuel Reid
  • 1,708
  • 11
  • 21
1

Focus does't imply that your page is scrolled to the element and is actually often used for form controls to gain the cursor.

What you need is actually a scrollToElement() function that calculates the page offset of your newly created div and scrolls the page to that position, a good one is described here : jQuery scroll to element

Community
  • 1
  • 1
Tiberiu C.
  • 2,943
  • 26
  • 37
0

Another thing you could do is add the tabindex attribute to the div element. This will enable the focus method to execute and find it and automatically move to it.

<div id="message-display-area" tabindex=1000>...</div>

JSFiddle to show it working.

Justin
  • 3,289
  • 3
  • 14
  • 26