EN
HTML - inline onclick function
0
points
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>