[Learning]#24 JS: HTML DOM Events — Part 2

Vida Lin
2 min readOct 13, 2021

Simple example of event handling

<!DOCTYPE html>
<html>
<head>
<title>JS - HTML DOM Events - Part 2-1</title>
<script type="text/javascript">
function over(element){
element.style.color="orange";
}
function out(element){
element.style.color="black";
}
</script>
</head>
<body style="font-family:Arial";>
<button onclick="alert('Clicked');">Click</button> <!-- Registering an event -->
<span onmouseover="over(this);"
onmouseout="out(this);">Get your cursor here to know my real color.</span>
<div onmouseover="over(this);"
onmouseout="out(this);">Closer, closer, closer!</div>

</body>
</html>

When it comes to event handling, “this” represents the objects.

Advanced example of event handling

<!DOCTYPE html>
<html>
<head>
<title>JS - HTML DOM Events - Part 2-2</title>
<script type="text/javascript">
// Advanced way to register an event dynamically through JS.
function init(){ //init = initialization
var btn=document.getElementById("btn");
var handler=function(){ // prepare a event listener, aka a event handler
alert("Clicked");
}
btn.addEventListener("click"/*event name*/, handler);
}
</script>
</head>
<body onload="init();"> <!-- Statically register the "load" event on <body>. Onload event will be initialized once the webpage is fully loaded. -->
<button id="btn">Click</button>


</body>
</html>

Music of Today: The List by Moonchild

Clap/Share/Follow

If you guys find this article helpful, please kindly do the writer a favor — giving 5 clicks at the GREEN area and 10~50 claps at the bottom of this page.

Most important of all, feel free to comment and share your ideas below to learn together!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Vida Lin
Vida Lin

Written by Vida Lin

PM, Relationship, Travel, or anything quirky but interesting.|Subscribe & buy Vida a drink @LikerLand, the bottom of each article. 在文章底下LikerLand訂閱、請Vida喝一杯飲料 ❤

No responses yet

Write a response