I am a js newbie and I’m trying to grasp inline vs. traditional registration. Code block 1 (inline) works fine, but code block 2 (traditional) does not. Can anyone shed light on my error?
<html>
<head>
<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/md5.js"></script>
<script>
function gethash() {
var name=prompt("Please enter your name","Harry Potter");
var hash = CryptoJS.MD5(name);
alert("Hello, " + name +".\nYour hash is " + hash)
}
</script>
</head>
<body>
<input type="button" onclick="gethash()" value="Get your hash" />
</body>
</html>
This attempt to use traditional registration does not work:
<html>
<head>
<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/md5.js"></script>
<script type="text/javascript">
function gethash() {
var name=prompt("Please enter your name","Harry Potter");
var hash = CryptoJS.MD5(name);
alert("Hello, " + name +".\nYour hash is " + hash)
}
document.getElementById('myname').onclick = gethash;
</script>
</head>
<body>
<input type="button" value="Get your hash" id="myname" />
</body>
</html>
There is no such element at the point where you’re trying to bind something using
onclick. Move that line to the bottom of the file.If you look at the console, you should see an error like:
This should fix it:
That leads us to the better way of doing this. Using
window.onload, you can execute the JS code after everything has loaded.