How to Make Button onclick in HTML

The onclick attribute is an event attribute supported by all browsers. It appears when a user clicks on a button element. If you want to make a button onclick, you need to add the onclick event attribute to the <button> element.

The button onclick runs a script when a button is clicked. Let’s see an example where we have a button, clicking on which will take you to our website. To achieve this, we just added the URL of the website to the window object.

Example

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <button onclick="window.location.href = 'https://w3docs.com';">Click Here</button>
  </body>
</html>

You can also use a button onclick in order to know the current date just by adding "getElementById('demo').innerHTML=Date()" to the onclick event.

Example

<!DOCTYPE html>
<html>
  <body>
    <p>Click the button to see the current date.</p>
    <button onclick="getElementById('demo').innerHTML=Date()">What day is today?</button>
    <p id="demo"></p>
  </body>
</html>

The onclick event is used to activate a function when an element is clicked. That is why it is mostly used with the JavaScript function. Let’s consider an example where you need to click the button to set a function that will output a message in a <p> element with id="demo".

Example

<!DOCTYPE html>
<html>
  <body>
    <p>There is a hidden message for you. Click to see it.</p>
    <button onclick="myFunction()">Click me!</button>
    <p id="demo"></p>
    <script>
      function myFunction() {
        document.getElementById("demo").innerHTML = "Hello Dear Visitor!</br> We are happy that you've chosen our website to learn programming languages. We're sure you'll become one of the best programmers in your country. Good luck to you!";
      }
    </script>
  </body>
</html>