The focus()
method sets focus to an element.
focus |
Yes | Yes | Yes | Yes | Yes |
HTMLElementObject.focus()
None
No return value.
The following code shows how to Give focus to an <a> element:
<!DOCTYPE html>
<html>
<head>
<style>
a:focus, a:active {<!-- w ww .jav a 2s.co m-->
color: green;
}
</style>
</head>
<body>
<a id="myAnchor" href="http://www.example.com">Visit</a>
<input type="button" onclick="getfocus()" value="Get focus">
<input type="button" onclick="losefocus()" value="Lose focus">
<script>
function getfocus() {
document.getElementById("myAnchor").focus();
}
function losefocus() {
document.getElementById("myAnchor").blur();
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to set focus to a text field.
<!DOCTYPE html>
<html>
<body>
<!--from www.ja va 2 s . c o m-->
<input type="text" id="myText" value="A text field">
<button type="button" onclick="getFocus()">Get focus</button>
<button type="button" onclick="loseFocus()">Lose focus</button>
<script>
function getFocus() {
document.getElementById("myText").focus();
}
function loseFocus() {
document.getElementById("myText").blur();
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to set focus to a text field immediately after the document window has been loaded.
<!DOCTYPE html>
<html>
<body>
<input type="text" id="myText" value="A text field">
<!-- ww w .j ava 2 s . c o m-->
<script>
window.onload = function() {
document.getElementById("myText").focus();
};
</script>
</body>
</html>
The code above is rendered as follows: