Simple javascript DOM event

<!DOCTYPE html>
<html>
<body>

<h1 onclick="this.innerHTML = 'You clicked'">Click on this text</h1>

</body>
</html>

In the following example, the onclick event calls a function ‘changetheText’.

<!DOCTYPE html>
<html>
<body>

<h1 onclick="changetheText(this)">Click on this text</h1>

<script>
function changetheText(id) {
  id.innerHTML = "You clicked";
}
</script>

</body>
</html>

The (this) word above allows the function to identify which text the function is being called from. Check out the following code:

<!DOCTYPE html>
<html>
<body>

<h1 onclick="changetheText(this)">Click on this text</h1>

<h1 onclick="changetheText(this)">Click on this text as well</h1>

<script>
function changetheText(id) {
  id.innerHTML = "You clicked";
}
</script>

</body>
</html>

Leave a Reply