JavaScript onclick Event

You are Here:

JavaScript onclick Event

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

onclick Event as Attribute


HTML Online Editor
<!DOCTYPE html> <html> <body> <p onclick="myFunction()">Click this paragraph</p> <script> function myFunction(){ document.write("You clicked"); } </script> </body> </html>


As Attribute

<element onclick = "JavaScript">

As Property

object.onclick = function(){ // code };

Using Event Listener

object.addEventListener("click" , myScript);

onclick Event as Property


HTML Online Editor
<!DOCTYPE html> <html> <body> <p>Click anywhere in this example.</p> <p id="point"></p> <script> var x = document.getElementById("point"); document.onclick = findAxis; function findAxis(e) { x.textContent = "Position ("+e.clientX+", "+e.clientY+")"; } </script> </body> </html>

Using addEventListener() Method

Note: The addEventListener() method is not supported in Internet Explorer 8 and below.


HTML Online Editor
<!DOCTYPE html> <html> <body> <p>Click on the button to alert.</p> <button>Click Me</button> <script> var x = document.getElementsByTagName("button")[0]; function myFunction(){ alert("You clicked the button"); } x.addEventListener("click", myFunction); </script> </body> </html>

click Event with this Keyword

In the following example, this keyword is used to find the specific element to which the event (click) occurred.


HTML Online Editor
<!DOCTYPE html> <html> <body> <h3 onclick="myFunction(this)">Click this heading</h3> <p onclick="myFunction(this)">Click this paragraph</p> <script> function myFunction(elmnt){ = "none"; } </script> </body> </html>

click Event with JavaScript as Value

Note: You can use any JavaScript in the HTML attribute value.


HTML Online Editor
<!DOCTYPE html> <html> <body> <p onclick="alert(new Date())">Click to Display time</p> </body> </html>


Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author