CSS Portal

HTML onclick Event Attribute

☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee
onclick
HTML Event AttributeThis event attribute is supported by all modern browsers.
Updated 13th October 2023

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>
Open in editor

Browser Support

The following information will show you the current browser support for the HTML onclick event attribute. Hover over a browser icon to see the version that first introduced support for this HTML event attribute.

This event attribute is supported by all modern browsers.

Desktop

Chrome
Edge
Firefox
Opera
Safari

Tablets & Mobile

Chrome Android
Firefox Android
Opera Android
Safari iOS
Samsung Internet
Android WebView
-
Supported Unknown Not supported
☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee