Languages
[Edit]
EN

HTML - inline onclick function

0 points
Created by:
Walter
586

In this article, we would like to show you how to create inline function and assign it to onclick event in HTML.

Quick solution:

<div onclick="console.log('Hello World!')">Click me!</div>

 

Practical example

In this section, we present a runnable example of defining a function inside onclick attribute.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div onclick="var x = 2; console.log(x);">Click me!</div>
</body>
</html>

Note:

Each onclick creates its own scope.

Calling function from <script> element

In this example, we present how to call a function defined inside <script> element.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <script>

    function sayHello() {
        console.log('Hello World!');
    };

  </script>
  <div onclick="sayHello()">Click me!</div>
</body>
</html>

 

Alternative titles

  1. HTML - execute inline onclick function
  2. HTML - execute inline function on click event
  3. HTML - create inline function and assign it to onclick event
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join