JavaScript iRock of Head First JavaScript


rock

Here is an example of JavaScript in action from the book Head First JavaScript by Michael Morrison, Publisher: O’Reilly Media, 2007. This book is no longer in print and has been replaced by the book Head First JavaScript Programming. The rock is just a png image that was uploaded to the WordPress Media Library and inserted into this post with a little styling.

When you click the rock image you are asked for your name. You are given a greeting and then the image changes to a smiling rock. We need to be sure that we first give the rock image an id.

For example, id=”rockImg” will be added to the tag. We also add the onclick event. Below is the HTML code that was used in this post.

<div style="margin-top:20px; text-align:center">
<img id="rockImg" src="http://porterwebsites.com/wp-content/uploads/2016/07/rock.png" alt="rock" width="227" height="190" size-full wp-image-3855" onclick="touchRock()" />
</div>

This id is how the JavaScript code finds which image we are referring to. Below is the JavaScript code.

function touchRock() {
   var userName = prompt("What is your name?", "Enter your name here");
   if (userName) {
      alert("It is good to meet you, " + userName + ".");
	  document.getElementById("rockImg").src = "http://porterwebsites.com/wp-content/uploads/2016/07/rock_happy.png";
   }
}

Below is what the prompt looks like using Windows 10.

JavaScriptPrompt

A Better Way

The web site wpbeginner.com has an article showing us a better way to add our JavaScript files to our WordPress sites. That won’t be discussed here, however we do discuss it in our Enqueue post.

Leave a comment

Your email address will not be published. Required fields are marked *