About Lesson
OnClick
Contoh 1′
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onclick Attribute</h2>
<button onclick="document.getElementById('demo').innerHTML=Date()">The time is?</button>
<p id="demo"></p>
</body>
</html>
Contoh 2
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onclick Attribute</h2>
<p>Click the button to display the date.</p>
<button onclick="displayDate()">The time is?</button>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
<p id="demo"></p>
</body>
</html>
Mouse Over
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Events</h1>
<h2>The mouseover and mousout Events</h2>
<div id="box"
style="width:200px;height:100px;padding:16px;border:1px solid #000;">
Move mouse over this box!
</div>
<script>
const box = document.getElementById("box");
// Let box listen for mouseover
box.addEventListener("mouseover", function () {
box.innerHTML = "Mouse is over me!";
});
// Let box listen for mouseout
box.addEventListener("mouseout", function () {
box.innerHTML = "Mouse is out!";
});
</script>
</body>
</html>
Mouse Position
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Events</h1>
<h2>The mousposition Event</h2>
<p id="demo">Move the mouse in this window!</p>
<script>
// Let document listen for mousemove
document.addEventListener("mousemove", function (event) {
document.getElementById("demo").innerHTML =
"X: " + event.clientX + " Y: " + event.clientY;
});
</script>
</body>
</html>
KeyDown
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Events</h1>
<h2>The keydown Event</h2>
<input id="k" type="text" placeholder="Press a key here!">
<p id="demo"></p>
<script>
const k = document.getElementById("k");
// Let k listen for keydown
k.addEventListener("keydown", function (event) {
document.getElementById("demo").innerHTML = "You pressed: " + event.key;
});
</script>
</body>
</html>
Load
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Events</h1>
<h2>The load Event</h2>
<p id="demo"></p>
<script>
// Add Event Listener to window
window.addEventListener("load", function () {
document.getElementById("demo").innerHTML = "Page is fully loaded!";
});
</script>
</body>
</html>
Timer
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Events</h1>
<h2>The setInterval() Method</h2>
<p id="clock"></p>
<script>
// Call showTime every 1000 millisec
setInterval(showTime, 1000);
// Function to display the time
function showTime() {
const d = new Date();
document.getElementById("clock").innerHTML =
d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
}
</script>
</body>
</html>