tigerden
tigerden

Reputation: 728

remove focus from an HTML element on load

I am using this theme for my website and I have customised its contents. I have added one more slide (fragment), on for login form. However, due to the username input field in this form, whenever the page loads, the focus shifts from home fragment to this username field and the page looks skewed. I tried adding a hidden field hiddenfield in the first home fragment and writing

<body onload="setfocus()">

where setfocus() is

function setfocus() {
    document.getElementById("hiddenfield").focus();
}

but it didn't work.

In short, I need to remove the default focus from an inputbox on page and give it to a fragment. How to do this? Please help as I need to fix this issue immediately.

Upvotes: 0

Views: 4127

Answers (3)

user2793390
user2793390

Reputation: 771

I haven't been able to reproduce the default focus to the input field, but if you add an id attr to the element you want to be at the top of the page, you should be able to navigate to it after the page loads.

<html>
<head>
<script type="text/javascript">
    window.onload = function(){
        window.location.hash = '#divToFocus';
    }
</script>
</head>
<body>
<div id="divToFocus">fasdfsdfsd</div>   
<form action="action">
    <fieldset>
        <legend>Personal information:</legend>
        Name: <input type="text" size="30" /><br />
        E-mail: <input type="text" size="30" /><br />
        Date of birth: <input type="text" size="10" />
    </fieldset>
</form>
</body>
</html>

Upvotes: 1

Ted
Ted

Reputation: 14937

Try window.focus() instead of the hidden element

Upvotes: 0

Albzi
Albzi

Reputation: 15619

JsFiddle

Try this in either <script> tags or seperate .js file.

(function() {
   document.getElementById("hiddenfield").focus();
})();

or:

<!DOCTYPE html>
<html>
<head>
<script>
function setFocus()
{
    document.getElementById("hiddenfield").focus();
}
</script>
</head>

<body onload="setFocus()">
<!-- stuff here -->
</body>

</html>

Upvotes: 0

Related Questions