I am learning event handlers and doing these exercises from the JavaScript and jQuery book by Jon Duckett. I am using Firefox, but tried it in Chrome too.
This is the function that does work and is using HTML event handler, if I understand correctly:
function checkUsername() {
var elMsg = document.getElementById("feedback");
var elUsername = document.getElementById("username");
if (elUsername.value.length < 5) {
elMsg.innerHTML = "Not long enough";
} else {
elMsg.innerHTML = "";
}
}
This is the DOM event handler, which I understand is safer, and it doesn't work, and I can't figure out why:
function checkUsername() {
var elMsg = document.getElementById("feedback");
if (this.value.length < 5) {
elMsg.innerHTML = "Not long enough";
} else {
elMsg.innerHTML = "";
}
}
var el = document.getElementById("username");
el.addEventListener("blur", checkUsername, false);
This is the HTML markup:
<!DOCTYPE html>
<html>
<head>
<title>Events</title>
<link rel="stylesheet" href="css/06.css" />
<script type="text/javascript" src="js/event.js"></script>
</head>
<form method="post" action="http://www.example.org/register">
<label for="username">Create a username: </label>
<input type="text" id="username" onblur="checkUsername()" />
<div id="feedback"></div>
<label for="password">Create a password: </label>
<input type="password" id="password" />
<input type="submit" value="Sign up!" />
</form>
</body>
</html>
Actually all the examples from events on, from page 253 on (event-handler, you can find everything on its website) don't work ... I looked if JavaScript is enabled and it is, when I typed javascript.enabled
in about:config
. Can anyone help me why this is not working?
` tag. Putting `script` elements in the `head` is an anti-pattern.
– T.J. Crowder Sep 08 '15 at 17:28