JavaScript focus method

Ads
 

JavaScript focus method

JavaScript focus method can be used to set focus to the current window, to the input text box , to the specific button or to any radio button and many more elements.

JavaScript focus method can be used to set focus to the current window, to the input text box , to the specific button or to any radio button and many more elements.

JavaScript focus method

     

JavaScript focus method can be used to set focus to the current window, to the input text box , to the specific button or to any radio button and many more elements. This provides the programmer to create a user-friendly code to work with. Here in this part of JavaScript methods tutorial we are providing you a simple example to set the focus to the input text box. Not only it will set the focus to the input text box, at the same time it will input the text "RoseIndia" in the input box.

Syntax:

 element_Object.focus();

Where element_Object is the element to whom we have to set focus for further working.

Description of Code

In the following code we have created the function setFocus() in the JavaScript to show the use of "focus()" method. This function would be called when any user clicks on the button "Set Focus !" or when user focuses the given input text box. Given below is the html code for focusExample.html

 <html>
<body>
<script language="JavaScript">
  function setFocus() {
  document.getElementById('txt').focus();
   document.getElementById('txt').value='RoseIndia';
  }
</script>
<div style="background: #cf2255; width:'100%';" align="center">
  <font color="#05ff20" size="12pt">
   <b>Focus Example</b>
  </font>
</div>
<center>
  <div style="background: #ffffcc; width:'100%';" align="center">
   <input  id="txt" type="text" value="" onFocus="setFocus();"/>
   <input  type="button" value="Set Focus !" onclick="setFocus();"/>
  <div>
</body>
</html>

Output :

click on the Set Focus! button to set the focus to the text box.

It will write text "RoseIndia" in the text box and as well as set focus to the last of the text box character position. You can also download the html code.

Download Source Code

     

Ads

Ads