Cyber Week

Save big!

All courses under $5 - for a limited time!

Code has been added to clipboard!

onclick

Reading time 2 min
Published Aug 10, 2017
Updated Oct 10, 2019

onclick JavaScript: Main Tips

  • The onclick JavaScript event occurs when the user clicks on an element.
  • It runs a specified line of code when you click a HTML object that has the onclick attribute.
  • The JavaScript onclick functions can be triggered by object.onclick or object.addEventListener.
  • The addEventListener method is not supported by earlier versions of Internet Explorer (8 and below).

Syntax and Usage of onclick

The following code snippets demonstrate the proper syntax of applying the JavaScript button onclick event. You should specify the object you want to affect and indicate the onclick function in JavaScript you wish to execute.

Regular syntax: object.onclick = function(){my_script};

Using the addEventListener method: object.addEventListener("click", my_script);

Example shows the current date when text was clicked:

Example
<button onclick="getElementById('test').innerHTML = Date()">This will show date when clicked.</button>

See how this example changes the text color when clicked:

Example
function myFunction() {
    document.getElementById("test").style.color = "red";
}

The code in next example also changes text color, but does it by using a slightly different method:

Example
function myFunction(element,clr) {
    element.style.color = clr;
}

In the example below, copies text on click:

Example
function myFunction() {
    document.getElementById("field2").value = document.getElementById("field1").value;
}

Clicking changes the color of the background in our window.onclick example:

Example
window.onclick = myFunction;
function myFunction() {    
  document.getElementsByTagName("BODY")[0].style.backgroundColor = "lime";   
}

When onclick Is Used

The JavaScript onclick event is one of the most frequently utilized event types. It's a common practice to enhance websites by adding some functionality such as JavaScript button click or other elements.

The JavaScript onclick function is designed to execute code when users interact with the HTML elements. The onclick JavaScript can be applied to any HTML element.