CoffeePeddlerIntern
CoffeePeddlerIntern

Reputation: 679

Setting focus to a div after show

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

Upvotes: 1

Views: 4857

Answers (4)

Justin
Justin

Reputation: 3397

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.

Upvotes: 0

Samuel Reid
Samuel Reid

Reputation: 1756

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();
});

Upvotes: 2

Kevin Boucher
Kevin Boucher

Reputation: 16675

Replace this line:

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

with this line:

window.location.hash = "message_display_area";

Upvotes: 3

Tiberiu C.
Tiberiu C.

Reputation: 3513

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

Upvotes: 1

Related Questions