Appearance
How to Make Button onclick in HTML
The onclick attribute is an event attribute that is supported by all browsers. It triggers when the user clicks on a button element. If you want to handle a button click, you need to add the onclick event attribute to the <button> element.
How to add URL to the window object
The button onclick attribute executes a script when the user clicks a button. Let’s see an example where clicking a button navigates to our website. To achieve this, we'll set the window.location.href property to the website URL.
Example of adding URL to the window object:
Example of button with onclick attribute
html
<!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 to display the current date by adding document.getElementById('demo').innerHTML = Date(); to the onclick event.
Example of using a button onclick to know the current date:
Example of button onclick which is used to know the current date
html
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<p>Click the button to see the current date.</p>
<button onclick="document.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 clicking the button calls a function that displays a message in a <p> element with id="demo".
Example of adding an onclick event:
Example of button onclick which calls the function
html
<!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>Note: For modern web development, it is recommended to use
addEventListenerinstead of inlineonclickattributes to keep HTML and JavaScript separate.