Cover Image for JavaScript onclick event
112 views

JavaScript onclick event

The onclick event in JavaScript is used to trigger a function or perform an action when an element is clicked. It can be used with various HTML elements such as buttons, links, images, etc.

Here’s an example of how to use the onclick event in JavaScript:

HTML<span role="button" tabindex="0" data-code="<button onclick="myFunction()">Click me</button> <script> function myFunction() { // Code to be executed when the button is clicked alert("Button clicked!"); }
<button onclick="myFunction()">Click me</button>

<script>
function myFunction() {
  // Code to be executed when the button is clicked
  alert("Button clicked!");
}
</script>

In the example above, the onclick attribute is added to the <button> element. When the button is clicked, the myFunction() function is called, and an alert box displaying “Button clicked!” will be shown.

You can also assign the event handler using JavaScript instead of inline HTML attributes. Here’s an alternative way to achieve the same result:

HTML<span role="button" tabindex="0" data-code="<button id="myButton">Click me</button> <script> document.getElementById("myButton").onclick = function() { // Code to be executed when the button is clicked alert("Button clicked!"); };
<button id="myButton">Click me</button>

<script>
document.getElementById("myButton").onclick = function() {
  // Code to be executed when the button is clicked
  alert("Button clicked!");
};
</script>

In this approach, the onclick event handler is assigned to the button using JavaScript. The getElementById() method is used to select the button element based on its id attribute, and the event handler function is defined inline.

You can customize the myFunction() or the anonymous function to perform any desired action when the element is clicked.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS