The onclick
attribute is an event attribute that is supported by all HTML elements. It specifies the script to run when the element is clicked.
Here is an example of how to use the onclick
attribute in an HTML button element:
<button onclick="alert('Button clicked!')">Click me</button>
Code language: HTML, XML (xml)
When the button is clicked, an alert message will be displayed saying “Button clicked!”.
Redirecting When Button Clicked
To redirect to another page when a button is clicked, you can use the window.location
object in JavaScript. Here is an example:
<button onclick="redirect()">Click me</button>
<script>
function redirect() {
window.location = "http://www.example.com";
}
</script>
Code language: HTML, XML (xml)
Or, more simply:
<button onclick="window.location='http://www.example.com'">Click me</button>
Code language: HTML, XML (xml)
Calling Functions
You can also use the onclick
attribute to call a function in your JavaScript code:
<button onclick="sayHello()">Click me</button>
<script>
function sayHello() {
alert('Hello');
}
</script>
Code language: HTML, XML (xml)
In this example, the sayHello
function will be called when the button is clicked.
Leave a Reply