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:
xxxxxxxxxx
1
<div onclick="console.log('Hello World!')">Click me!</div>
In this section, we present a runnable example of defining a function inside onclick
attribute.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div onclick="var x = 2; console.log(x);">Click me!</div>
5
</body>
6
</html>
Note:
Each
onclick
creates its own scope.
In this example, we present how to call a function defined inside <script>
element.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<script>
5
6
function sayHello() {
7
console.log('Hello World!');
8
};
9
10
</script>
11
<div onclick="sayHello()">Click me!</div>
12
</body>
13
</html>