1017 Head First HTML5 Programming — Study Log #4
Chapter 3. Events, Handlers and All that Jazz: A Little Interaction
- Inserted code into your page.
- Set up a button click event and written the code to capture and handle the button click.
- Asked the DOM for information.
- Created and added new elements to the DOM.
- There are lots of events happening in your browser all the time. If you want to respond to these events, you need to handle the events with event handlers.
- A button click event is triggered when you click on a button in a web page.
-
You handle a button click event by registering a function to handle the event. You do this by writing a function, and setting the button’s onclick property to the function name.
- To get the text a user has typed into a form input text field, you use the input’s value property.
- If a user has not entered anything into a form input text field, the value of the field will be the empty string
(“”). -
You can compare a variable to the empty string using an
iftest and==. - To add a new element to the DOM, you first need to create the element and then add it as a child of an element.
- Use
document.createElementto create a new element. Pass the tag name (e.g., “li”) into the function call to indicate what element to create. - To add an element as a child of a parent element in the DOM, get a reference to the parent, and call
appendChildon the parent, passing in the child element you’re adding. -
If you add multiple children to a parent by using appendChild, each new child is appended after the other children, so they appear after or below the other children in the page (assuming you’re not changing the layout with CSS).
- You can use the Web Storage API (localStorage) to store data in a user’s browser.
<!doctype html>
<html lang="en">
<head>
<title>Webville Tunes</title>
<meta charset="utf-8">
<script src="playlist_store.js"></script>
<script src="playlist.js"></script>
<link rel="stylesheet" href="playlist.css">
</head>
<body>
<form>
<input type="text" id="songTextInput" size="40" placeholder="Song name">
<input type="button" id="addButton" value="Add Song">
</form>
<ul id="playlist">
</ul>
</body>
</html>
window.onload = init;
function init() {
var button = document.getElementById("addButton");
button.onclick = handleButtonClick;
loadPlaylist();
}
function handleButtonClick() {
var textInput = document.getElementById("songTextInput");
var songName = textInput.value;
var li = document.createElement("li");
li.innerHTML = songName;
var ul = document.getElementById("playlist");
ul.appendChild(li);
save (songName);
if (songName== ""){
alert("Please enter a song");
} else {
alert("Adding " + songName);
}
}