HTML DOM Button autofocus Property


The HTML DOM Button autofocus property is associated with autofocus property of the <button> element. The button autofocus property is used to specify whether a button on the HTML document should get the focus or not when the page loads.

Syntax

Following is the syntax for −

Setting the button autofocus property −

buttonObject.autofocus = true|false

Here, the true|false specifies if the given input button should get the focus on not when the page loads.

  • True − Input button gets focus
  • False Input button doesn’t get focus.

Example

Let us see an example for the HTML DOM button autofocus property −

<!DOCTYPE html>
<html>
<body>
<button type="button" id="MyButton" autofocus>BUTTON</button>
<p>Click the below button to know if the input button above automatically gets the focus on page load or not</p>
<button onclick="buttonFocus()">CLICK IT</button>
<p id="Sample"></p>
<script>
   function buttonFocus() {
      var x = document.getElementById("MyButton").autofocus;
      if(x==true)
         document.getElementById("Sample").innerHTML="The input button does get focus on page load";
      else
         document.getElementById("Sample").innerHTML="The input button does not get focus on
      page load";
   }
</script>
</body>
</html>

Output

This will produce the following output −

On clicking CLICK IT button −

In the above example −

We have a button with id “MyButton” and autofocus property enabled −

<button type="button" id="MyButton" autofocus>BUTTON</button>

We then have a CLICK IT button to execute buttonFocus() function −

<button onclick="buttonFocus()">CLICK IT</button>

The buttonFocus() function gets the button element using the getElementById() method and gets its autofocus value, which is Boolean and assigns it to the variable x. Using the conditional statements we check whether the autofocus value is true and false and display suitable text accordingly in a <p> element with id “Sample” associated with it.

function buttonFocus() {
   var x = document.getElementById("MyButton").autofocus;
   if(x==true)
      document.getElementById("Sample").innerHTML="The input button does get focus on page load";
   else
      document.getElementById("Sample").innerHTML="The input button does not get focus on page load";
}

Updated on: 06-Aug-2019

103 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements