[Learning]#23 JS: HTML DOM Events — Part 1

Vida Lin
2 min readOct 12, 2021

What is the Event?

“HTML DOM events allow JavaScript to register different event handlers on elements in an HTML document.
Events are normally used in combination with functions, and the function will not be executed before the event occurs (such as when a user clicks a button).”

by W3C School

Example: unfolding/folding a menu

Before: unfold

After: folding

The way I coded:

<!DOCTYPE html>
<html>
<head>
<title>JS - HTML DOM Events - Part 1</title>
<script type="text/javascript">
function toggleMenu(number) { //With the argement, nember, toggleMenu can get the relating list.
var menu=document.getElementById("menu"+number);
menu.classList.toggle("hide"); //toggle is for controlling the "hide" class setting.
/*
if(menu.style.display=="none") {//means that it's hidden now.
menu.style.display=="block";
}
else{//means that it's displaying now.
menu.style.display=="none";
}
menu.innerHTML=""; //innerHTML is a property for us to easily modify the content of an HTML element.
menu.style.fontFamily="Arial";
menu.style.display=none;
*/

}

</script>
<style type="text/css">
.hide{display:none;}
/*With this class selector and the we don't need the if statement above.*/
</style>
</head>
<body style="font-family:Arial">
<div onclick="toggleMenu(1);">Auntie Style</div>
<ul id="menu1">
<li>Beef Noodle</li>
<li>Fried Shrimp Noodle</li>
</ul>
<div onclick="toggleMenu(2);">Uncle Style</div>
<ul id="menu2">
<li>Pork Noodle</li>
<li>Fried Squid Noodle</li>
</ul>
<div onclick="toggleMenu(3);">Grandparents Style</div>
<ul id="menu3">
<li>Happy Noodle</li>
<li>Surprise Noodle</li>
</ul>
</body>
</html>

Music of Today: Crush by Tessa Violet

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