<button onclick="hello()">Hello</button>
<script>
function hello() {
alert('Hello');
}
</script>
This is my code. But it's not working. When I click on the button nothing happens.
The onclick event executes a certain functionality when a button is clicked. This could be when a user submits a form, when you change certain content on the web page, and other things like that. You place the JavaScript function you want to execute inside the opening tag of the button.
Javascript has a built-in click() function that can perform a click in code. Let's see an example of this below.
The Html <button onclick=" "> is an event attribute, which executes a script when the button is clicked. This attribute is supported by all browsers. It is also used to call a function when the button is clicked.
Note to other developers coming across this, you can run into this if you use a reserved method names e.g. clear
.
<!DOCTYPE html>
<html>
<body>
<button onclick="clear()">Clear</button>
<button onclick="clear2()">Clear2</button>
<script>
function clear() {
alert('clear');
}
function clear2() {
alert('clear2');
}
</script>
</body>
</html>
How about this?
<button id="hellobutton">Hello</button>
<script>
function hello() {
alert('Hello');
}
document.getElementById("hellobutton").addEventListener("click", hello);
</script>
P.S. You should place hello() above of the button.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With