onclick Event
Example
Execute a JavaScript when a button is clicked:
More "Try it Yourself" examples below.
Definition and Usage
The onclick event occurs when the user clicks on an element.
Browser Support
Event | |||||
---|---|---|---|---|---|
onclick | Yes | Yes | Yes | Yes | Yes |
Syntax
In JavaScript, using the addEventListener() method:
Note: The addEventListener() method is not supported in Internet Explorer 8 and earlier versions.
Technical Details
Bubbles: | Yes |
---|---|
Cancelable: | Yes |
Event type: | MouseEvent |
Supported HTML tags: | All HTML elements, EXCEPT: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title> |
DOM Version: | Level 2 Events |
More Examples
Example
Click on a <button> element to display the current day, date and time:
Example
Click on a <p> element to change its text color to red:
<script>
function myFunction() {
document.getElementById("demo").style.color = "red";
}
</script>
Example
Another example on how to change the color of a <p> element by clicking on it:
<script>
function myFunction(elmnt,clr) {
elmnt.style.color = clr;
}
</script>
Example
Click on a button to copy some text from an input field to another input field:
<script>
function myFunction() {
document.getElementById("field2").value = document.getElementById("field1").value;
}
</script>
Example
Assign the "onclick" event to the window object:
// If the user clicks in the window, set the background color of <body> to yellow
function myFunction() {
document.getElementsByTagName("BODY")[0].style.backgroundColor = "yellow";
}
Example
Using onclick to create a dropdown button:
document.getElementById("myBtn").onclick = function() {myFunction()};
/* myFunction toggles between adding and removing the show class, which is used to hide and show the dropdown content */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
Related Pages
HTML DOM reference: ondblclick event
HTML DOM reference: onmousedown event
HTML DOM reference: onmouseup event
Event Object