Monday, June 17, 2019

Events in JavaScript

Events in JavaScript
The absolute coolest thing about JavaScript is its ability to help you create dynamic webpages that increase user interaction, making the visitor feel like the website is almost coming alive right before her eyes.

The building blocks of an interactive web page is the JavaScript event system. An event in JavaScript is something that happens with or on the webpage. A few example of events:

  •     A mouse click
  •     The webpage loading
  •     Mousing over a hot spot on the webpage, also known as hovering
  •     Selecting an input box in an HTML form
  •     A keystroke

A Couple of Examples Using Events
JavaScript has predefined names that cover numerous events that can occur, including the ones listed above. To capture an event and make something happen when that event occurs, you must specify the event, the HTML element that will be waiting for the event, and the function(s) that will be run when the event occurs.

We have used a JavaScript event in a previous lesson, where we had an alert popup when the button was clicked. This was an "onclick" JavaScript event. We will do that same example again, as well as the mouseover and mouseout events.

HTML & JavaScript Code:

<html>
<head>
<script type="text/javascript">
<!--
function popup() {
    alert("Hello World")
}
//-->
</script>
</head>
<body>

<input type="button" value="Click Me!" onclick="popup()"><br />
<a href="#" onmouseover="" onMouseout="popup()">
Hover Me!</a>

</body>
</html>

Display:

Click Me

Hover Me!


With the button we used the event onClick event as our desired action and told it to call our popup function that is defined in our header. To call a function you must give the function name followed up with parenthesis "()".

Our mouseover and mouseout events were combined on one HTML element--a link. We wanted to do nothing when someone put their mouse on the link, but when the mouse moves off the link (onMouseout), we displayed a popup.