onclick Event
Example
Execute a JavaScript when a button is clicked:
<button onclick="myFunction()">Click me</button>
Try it Yourself »
Definition and Usage
The onclick
event occurs when the user clicks on an element.
In JavaScript, using the addEventListener() method:
object.addEventListener("click", myScript);
Try it Yourself »
Technical Details
Bubbles: | Yes |
---|---|
Cancelable: | Yes |
Event type: | MouseEvent |
Supported HTML tags: |
All exept: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title> |
More Examples
Click a <button> to display the date:
<button onclick="getElementById('demo').innerHTML = Date()">What is the time?</button>
Try it Yourself »
Click a <h3> element to change the text color:
<h3 id="demo" onclick="myFunction()">Click me to change my color.</h3>
<script>
function myFunction() {
document.getElementById("demo").style.color = "red";
}
</script>
Try it Yourself »
Another example on how to change the color of an element:
<h3 onclick="myFunction(this, 'red')">Click me to change my color.</h3>
<script>
function myFunction(element, color) {
element.style.color = color;
}
</script>
Try it Yourself »
Click to copy text from one input field to another:
<button onclick="myFunction()">Copy Text</button>
<script>
function myFunction() {
document.getElementById("field2").value =
document.getElementById("field1").value;
}
</script>
Try it Yourself »
How to assign an "onclick" event to the window object:
window.onclick = myFunction;
function myFunction() {
document.getElementsByTagName("BODY")[0].style.backgroundColor = "yellow";
}
Try it Yourself »
Use onclick to create a dropdown:
document.getElementById("myBtn").onclick = function() {myFunction()};
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
Try it Yourself »
Related Pages
JavaScript Tutorial: JavaScript Events
HTML DOM reference: ondblclick event
HTML DOM reference: onmousedown event
HTML DOM reference: onmouseup event
Browser Support
onclick
is a DOM Level 2 (2001) feature.
It is fully supported in all browsers:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |