Create Your First HTML Button: Simple Tutorial with Example

First We Will create the most simple button with html without any functionality. That means it will just show the button and do nothing..



<!DOCTYPE html>
<html>
<head>
</head>
<body>

<button>Button</button>

</body>
</html>


    
    
    

From the code.

  • We set the button with button tag like this <button>Button Text</button>

This code is missing the functionality. That means we did not said the code when the user click on the button what should it do!

So in the next example we will add this functionality.

It will be like this. When the user click the button it will show this text “Hello User”



<!DOCTYPE html>
<html>
<head>
</head>
<body>

<button id="HelloButton">Button</button>
<p id="message"></p>

<script>
  var exampleButton = document.getElementById('HelloButton');

  exampleButton.addEventListener('click', function() {
    var messageParagraph = document.getElementById('message');
    messageParagraph.innerHTML = 'Hello User';
  });
</script>

</body>
</html>





    
    
    

From The code

When the user click the button it triggers the JavaScript function and find the message id and include the text inside the paragraph tag.

In the Next Example We added some css of button.

Here the color means the font color

Now add some design in the button




<!DOCTYPE html>
<html>
<head>
  <style>

    #HelloButton {
      padding: 10px 20px;
      background-color: black;
      color:white;
      font-size: 16px;
    }

    #message {
      font-size: 18px;
      margin-top: 10px;
    }
  </style>
</head>
<body>

<button id="HelloButton">Button</button>
<p id="message"></p>

<script>
  var button = document.getElementById('HelloButton');
  var messageParagraph = document.getElementById('message');

  button.addEventListener('click', function() {
    messageParagraph.innerHTML = 'Hello User';
  });
</script>

</body>
</html>



    
    
    

Test the code here. Excersise the example instantly..