onclick Event
Example
Call a function when a button is clicked:
More examples below.
Description
The onclick event occurs when the user clicks on an HTML element.
Mouse Events
| Event | Occurs When |
|---|---|
| onclick | The user clicks on an element |
| oncontextmenu | The user right-clicks on an element |
| ondblclick | The user double-clicks on an element |
| onmousedown | A mouse button is pressed over an element |
| onmouseenter | The pointer is moved onto an element |
| onmouseleave | The pointer is moved out of an element |
| onmousemove | The pointer is moving over an element |
| onmouseout | The mouse pointer moves out of an element |
| onmouseover | The mouse pointer is moved over an element |
| onmouseup | The mouse button is released over an element |
See Also:
Tutorial:
Syntax
In JavaScript, using the addEventListener() method:
Technical Details
| Bubbles: | Yes |
|---|---|
| Cancelable: | Yes |
| Event type: | MouseEvent |
| Supported HTML tags: |
All except: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title> |
More Examples
Click a <button> to display the date:
Click a <h3> element to change the text color:
<script>
function myFunction() {
document.getElementById("demo").style.color = "red";
}
</script>
Another example on how to change the color of an element:
<script>
function myFunction(element, color) {
element.style.color = color;
}
</script>
Click to copy text from one input field to another:
function myFunction() {
document.getElementById("field2").value = document.getElementById("field1").value;
}
</script>
How to assign an "onclick" event to the window object:
function myFunction() {
document.getElementsByTagName("BODY")[0].style.backgroundColor = "yellow";
}
Use onclick to create a dropdown:
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
Browser Support
onclick is a DOM Level 2 (2001) feature.
It is fully supported in all browsers:
| Chrome | Edge | Firefox | Safari | Opera | IE |
| Yes | Yes | Yes | Yes | Yes | 9-11 |