onclick event

Definition and usage

The onclick event occurs when the user clicks an element.

Example

Execute JavaScript when the button is clicked:

<button onclick="myFunction()">Click me</button>

Try It Yourself

More TIY examples are at the bottom of the page.

Syntax

In HTML:

<element onclick="myScript">

Try It Yourself

In JavaScript:

object.onclick = function(){myScript};

Try It Yourself

In JavaScript, use the addEventListener() method:

object.addEventListener("click", myScript);

Try It Yourself

Note:Internet Explorer 8 and earlier versions do not support addEventListener() method.

Technical details

Bubble: Support
Cancelable: Support
Event types: 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

Browser support

Event Chrome IE Firefox Safari Opera
onclick Support Support Support Support Support

More examples

Example

Click the <button> element to display the current date and time:

<button onclick="getElementById('demo').innerHTML = Date()">What is the time?</button>

Try It Yourself

Example

Click the <p> element to change its text color to red:

<p id="demo" onclick="myFunction()">Click me to change my text color.</p>
<script>
function myFunction() {
  document.getElementById("demo").style.color = "red";
}
</script>

Try It Yourself

Example

Another example of how to change the color of a <p> element by clicking:

<p onclick="myFunction(this, 'red')">Click me to change my text color.</p>
<script>
function myFunction(elmnt,clr) {
  elmnt.style.color = clr;
}
</script>

Try It Yourself

Example

Clicking the button will copy some text from one input field to another input field:

<button onclick="myFunction()">Copy Text</button>
<script>
function myFunction() {
  document.getElementById("field2").value = document.getElementById("field1").value;
}
</script>

Try It Yourself

Example

Assign the "onclick" event to the window object:
window.onclick = myFunction;
// If the user clicks in the window, set the <body> background color to yellow
function myFunction() {
  document.getElementsByTagName("BODY")[0].style.backgroundColor = "yellow";
}

Try It Yourself

Example

Use onclick to create a dropdown button:

// Get the button, and when the user clicks on it, execute myFunction
document.getElementById("myBtn").onclick = function() {myFunction()};
/* myFunction toggles between adding and removing the show class, to hide and show the dropdown content */
function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

Try It Yourself

Related Pages

JavaScript Tutorial:JavaScript Event

HTML DOM Reference Manual:ondblclick Event

HTML DOM Reference Manual:onmousedown Event

HTML DOM Reference Manual:onmouseup Event