HTML onclick Event Attribute

Description

The onclick HTML event attribute specifies a JavaScript function that will be executed when the user clicks on an HTML element. It is a global attribute, meaning that it can be used on any HTML element, except for the <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title> elements.

The value of the onclick attribute is a string containing the name of the JavaScript function that will be executed. When the user clicks on the element, the JavaScript function will be called with the element as its argument.

The onclick event attribute is a very useful way to add interactivity to your web pages. It can be used to perform a variety of tasks, such as:

  • Changing the content of an element
  • Displaying a hidden element
  • Opening a new window or tab
  • Submitting a form
  • Playing a sound
  • Calling an API

Here is an example of how to use the onclick event attribute:

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

The JavaScript function myFunction() will be executed when the user clicks on the button. Here is an example of a JavaScript function that can be used with the onclick event attribute:

function myFunction() {
  alert("You clicked the button!");
}

This function will display an alert message when the user clicks on the button.

The onclick event attribute is a powerful tool that can be used to add interactivity and functionality to your web pages.

Syntax

<element onclick="script">

Values

  • scriptThe name of the script to use when the event has been triggered.

Example

<!DOCTYPE html> 
<html>
<head>
<title>Event attribute onclick</title>
</head>
<body>
<p id="demo">Click on the button to run the script:</p>
<button onclick="mouseTest1()">Click me!</button>
<script>
function mouseTest1 () {
var x = document.getElementById ("demo");
x.style.fontSize = "25px";
x.style.color = "orange";
x.style.backgroundColor = "#555555";
}
</script>
</body>
</html>

Browser Support

The following table will show you the current browser support for the HTML onclick Event Attribute.

Desktop
Edge Chrome Firefox Opera Safari
YesYesYesYesYes
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
YesYesYesYesYesYes

Last updated by CSSPortal on: 13th October 2023