onclick Event

The onclick event occurs when the user clicks on an HTML element.

Mouse Events

EventOccurs 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

object.onclick = function()myScript>;

In JavaScript, using the addEventListener() method:

object.addEventListener("click", myScript);

Technical Details

Bubbles: Yes
Cancelable: Yes
Event type: MouseEvent
Supported
HTML tags:
All except: , ,
, , , , , , , , and

More Examples

Click a to display the date:


Click a element to change the text color:

Click me to change my color.


Another example on how to change the color of an element:

Click me to change my color.


Click to copy text from one input field to another:

function myFunction() document.getElementById("field2").value = document.getElementById("field1").value;
>

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
W3schools Pathfinder Track your progress - it's free!

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.