Element Events

Goal

  • âš¡ Understand (2) of the below code
js-test1.html
<script>
let demoElement = document.getElementById("demo"); --- (1)
demoElement.onclick = function changeContent () { --- (2)
demoElement.innerHTML = "Help me"; --- (3)
demoElement.style = "color: red"; --- (3)
}
</script>

Overview

To understand (2) and (3) of the above code,

we're going to focus on <div#demo> Element and learn Element Events and Properties.

ELement Events

In this step, we focus on Element Events to understand (2).

As described here, HTML element have various "Events".

https://developer.mozilla.org/en-US/docs/Web/API/Element

And you can

Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface.

https://developer.mozilla.org/en-US/docs/Web/API/Element

note
  • I will handle addEventListener() in future step
  • Focus on oneventname property currently

Okay so, let's check the example of events.

click event

click:

Fired when a pointing device button (e.g., a mouse's primary button) is pressed and released on a single element. Also available via the onclick property.

This is what used in our code

<script>
let demoElement = document.getElementById("demo");
demoElement.onclick = function changeContent () {
demoElement.innerHTML = "Help me";
demoElement.style = "color: red";
}
</script>

Okay, so let's try another event.

mouseover event

mouseover:

Fired when a pointing device is moved onto the element to which the listener is attached or onto one of its children. Also available via the onmouseover property.

Try mouseover event

js-test1.html
<script>
let demoElement = document.getElementById("demo"); --- (1)
demoElement.onclick = function changeContent () { --- (2)
demoElement.innerHTML = "Help me"; --- (3)
demoElement.style = "color: red"; --- (3)
}
// you can skip function name
demoElement.onmouseover = function () {
console.log("Hello~!");
}
</script>

Javascript function

function is just a javascript syntax.

function functionName () {
// Do something here
}

https://www.w3schools.com/js/js_functions.asp

So, by writing like the below,

you can define "what to do" when there is an event to that Element.

SomeElement.oneventname = function functionName () {
// Do something here
}