How to Make Button onclick in HTML

The onclick attribute is an event attribute that is supported by all browsers. It appears when the 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.

How to add URL to the window object

The button onclick runs a script when the user clicks a button. Let’s see an example where we have a button, clicking on which you'll go to our website. To achieve this, we'll just add the URL of the website to the window object.

Example of adding URL to the window object:

<!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 of using a button onclick to know the current date:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <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 call 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 of adding an onclick event:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <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>