The onclick event occurs when the user clicks on an element.
onclick event can also use for below HTML tags:
All HTML elements, EXCEPT: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title>
<h2 id="demo" onclick="click_function()">Click me.</h2> <script> function click_function() { document.getElementById("demo").innerHTML = "HI...YOU CLICKED ME!"; } </script>
<h2 id="demo2" onclick="click_function2()">Try me.</h2> <script> document.getElementById("demo2").onclick = function() {click_function2()}; function click_function2() { document.getElementById("demo2").innerHTML = "HELLO USER......YOU CLICKED ME!"; } </script>
<h2 id="demo3" onclick="click_function2()">Click me.</h2> <script> document.getElementById("demo3").addEventListener("click", click_function3); function click_function3() { document.getElementById("demo3").innerHTML = "WHY YOU CLICKED ME!"; } </script>
<h2 id="demo4"></h2> <button class="btn btn-primary" onclick="getElementById('demo4').innerHTML=Date()">What is the time Now?</button>
<h2 id="demo5" onclick="change_color()">Click me to change my text color.</h2> <script> function change_color() { document.getElementById("demo5").style.color = "blue"; } </script>
Complete code for Onclick Event In JavaScript
<!DOCTYPE html> <html> <head> <title>Use Onclick Event In JavaScript</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> </head> <style> h1{ color: red; } </style> <body> <div class="container"> <br> <br> <div class="text-center"> <h1>Use Onclick Event In JavaScript</h1> </div> <br> <div class="well"> <h2 id="demo1" onclick="click_function1()">Click me.</h2> <h2 id="demo2" onclick="click_function2()">Try me.</h2> <h2 id="demo3" onclick="click_function2()">Click me.</h2> <h2 id="demo4"></h2> <h2 id="demo5" onclick="change_color()">Click me to change my text color.</h2> <button class="btn btn-primary" onclick="getElementById('demo4').innerHTML=Date()">What is the time Now?</button> </div> </body> </html> <script> function click_function1() { document.getElementById("demo1").innerHTML = "HI...YOU CLICKED ME!"; } document.getElementById("demo2").onclick = function() {click_function2()}; function click_function2() { document.getElementById("demo2").innerHTML = "HELLO USER......YOU CLICKED ME!"; } document.getElementById("demo3").addEventListener("click", click_function3); function click_function3() { document.getElementById("demo3").innerHTML = "WHY YOU CLICKED ME!"; } function change_color() { document.getElementById("demo5").style.color = "blue"; } </script>