hemc4
hemc4

Reputation: 1633

javascript focus not working on load

window.onload = function() {
                 try{

                     document.getElementById('result').focus();
                 }catch(err){

                 }

             }

In my form div result id load when form submits and when it show i want to focus on it. the above code is not working in my case. Please help me to find problem with this code.
jsfiddle

Upvotes: 0

Views: 1882

Answers (4)

dsgriffin
dsgriffin

Reputation: 68626

Here's a working jsFiddle.


1. Give the div a tab index of 0 (meaning it is ordered first):

<div class="result" tabindex="0" id="result">

(Find out more about the tabindex property here.)

2. Remove your <script> tags:

window.onload = function() {
    try{
        document.getElementById('result').focus();
    }catch(err){

    }                    
}

3. Use no wrap in <head> instead of onload.

Upvotes: 0

vdua
vdua

Reputation: 1331

You are trying to focus on a div, which by default can not be put to focus using script. To do that you need to set the tabindex attribute of the result div. You need to add the attribute tabindex and set its value to 0 and then your function document.getElementById().focus() will work

Also in your fiddle is not allowed inside javascript block. Try this fiddle

Upvotes: 0

Hieu Tran
Hieu Tran

Reputation: 150

You can not focus to a div element. But you can use

window.location.hash = '#result';

to scroll to div#result element

Upvotes: 1

Maloric
Maloric

Reputation: 5625

According to your jsFiddle, #result is a div. You can't really focus on a div the way you can with a form element or link, but you can jump to that part of the page using the following javascript instead:

window.location.hash = '#result';

Upvotes: 2

Related Questions