HTML event attribute onclick








The onclick attribute event is triggered when clicking a mouse button on the element.

What's new in HTML5

None.

Syntax

<element onclick="script or Javascript function name">

Supported Tags

All HTML elements, EXCEPT:

<base>, 
<bdo>, 
<br>, 
<head>, 
<html>, 
<iframe>, 
<meta>, 
<param>, 
<script>, 
<style>, 
<title>




Browser compatibility

onclick Yes Yes Yes Yes Yes

Example

<!DOCTYPE html>
<html>
<body>
<!--  w ww  .  j  a  va 2s.c o m-->
<button onclick="myFunction()">Click me</button>
<script>
function myFunction() {
    console.log("clicked");
}
</script>

</body>
</html>

Click to view the demo





Example 2

The following code shows how to handle mouse click event.

<html>
<head>
<script language="JavaScript">
  function addunderline() {<!--from w w w . jav a 2  s.  c om-->
    head1.style.textDecoration = "underline"
  }
  function removeunderline() {
    head1.style.textDecoration = "none"
  }

  function addoverline() {
    head1.style.textDecoration = "overline"
  }

  function addlinethrough() {
    head1.style.textDecoration = "line-through"
  }
</script>
</head>
<body>
  <h1 id="head1" 
      onMouseover="addunderline()"
    onMouseout="removeunderline()" 
    onClick="addoverline()"
    ondblclick="addlinethrough()">Welcome to this page!</h1>
  <P>A lot of interesting text goes here!</p>
</body>
</html>

Click to view the demo