Part 13 - Learning JavaScript for Beginners

Written by Eric Muss-Barnes, 20 December 2018

Ah, good old JavaScript. JavaScript has been around for a very long time. It was invented by Brendan Eich and first introduced into HTML in 1995.

What is JavaScript used for? What can it do?

Well, JavaScript is a very strange kind of programming language, and many developers learn it, and use it, without fully understanding the advantages and disadvantages of the capabilities of JavaScript.

So, let me break this lesson down into three parts.

1.) I will explain how JavaScript interacts with a webpage.

2.) I will explain what JavaScript should, and should not be used to accomplish, and why.

3.) I will show you a very easy example of how JavaScript is commonly used, even though it's not a very good idea to use it that way.

Note there is another programming language called "Java", and it has absolutely nothing whatsoever to do with JavaScript. So, don't get the two confused. Java and JavaScript are not the same thing, just like lightning and lightning bugs are not the same.

HOW DOES JAVASCRIPT INTERACT WITH A WEBPAGE?

In order to explain how and why JavaScript is useful (and when it is NOT useful) it is important to grasp how JavaScript interacts with the code of a webpage. While technology like HTML and CSS interact with the visible page and the visible code, JavaScript interacts with the sort of "backstage" area of a web browser. This area is called the "DOM" which is an abbreviation for the "Document Object Model". As usual, the computer nerds are trying to confuse us with haughty-sounding terminology, but it's a very simple concept. The DOM isn't a tangible part of a webpage. It's not a kind of code, or a new command, or a different language. The DOM is simply the computer nerd term for "the way a browser interprets what to do with HTML code".

Let me give an example, using something very simple.

Imagine we have a bold tag on a webpage. We already know what a bold tag looks like, and what it does.

The webpage is the Document.

The bold tag is the Object.

The browser knowing "I need to make this bold" is part of the way the browser will Model that object.

Does that make more sense?

So, a webpage is a "document", all the HTML elements on that page are the "objects", the internal processing of how to display those objects is the "model".

Makes sense now?

Another good analogy is a television set. We all know how a television works. A signal gets sent to the television, via the air or over a cable, the internal electronics interpret that signal, and process it into a picture on the screen. Think of your browser like a television set. The "signal" being sent to your browser is the code of a webpage. There is an internal processing component of your browser, which interprets that code, then shows it in your browser window. The DOM of a television would be the internal circuitry. The HTML and CSS of a television would be the image that appears on the screen.

The internal processing in a browser, which understands how to render HTML, is the "DOM" of the browser.

JavaScript can actually manipulate the DOM.

In other words, JavaScript can change things on a webpage, without changing the HTML.

How?

Because the JavaScript is changing the way the browser will MODEL the OBJECTS in the DOCUMENT.

Ah! Pretty wild! This is incredibly powerful and cool. But, as you can imagine, with great power comes great responsibility! Too many developers are abusing this power and they don't fully understand why it's a really bad idea to use JavaScript poorly. Sloppily manipulating the DOM is not a good thing and JavaScript is often a misused technology. Developers frequently use JavaScript to implement features which can more logically be done using other technologies, such as CSS or PHP.

What JavaScript should not be used for (but often is): Changing or displaying main body content.

What JavaScript should be used for: Powering interactive elements of a webpage.

Let me give you examples of both...

WHAT JAVASCRIPT IS FREQUENTLY USED FOR (BUT NEVER SHOULD BE):

  • Altering fonts... (use CSS instead)
  • Posting information from a database... (use XML or PHP instead)
  • Displaying a date on the page... (use PHP instead)
  • Writing data to the page from another file, such as a plain text or .JSON file... (use PHP instead)
WHAT JAVASCRIPT SHOULD BE USED FOR:
  • Building a calculator... (for example, an order form which totals your costs)
  • Creating an interactive map... (like the markers used in a Google Maps API)
  • Changing dynamic image links... (such as the "Watch Video" image on this webpage)
  • Tracking special parameters in links... (this was something we did at Disney, to track the popularity of links)

JavaScript should never (or very rarely) be used for passive content displayed on the page, only for interactive content.

What is the difference?

Why do I make these suggestions?

If JavaScript is capable of doing so much, why not use it for everything?

That is a valid question. In short, anything which renders to the page using JavaScript has at least three big problems:

1.) Since content is changed in the DOM, and not seen in the code, it will not be indexed by search engine spiders, so nothing you have built in JavaScript will help with SEO.

2.) Since your data is in a separate file from the HTML page (for example, if you are parsing information from a JSON file), if the user wants to save that webpage for later reference, they are unable to do so.

3.) Because you are dynamically changing the page content, it breaks the "BACK" button in the browser. For example, a user may click on a link, and be presented with an entirely new page of data. But when they click the "BACK" button in their browser, with the intent of returning to the previous page, they get sent to the previous website they had visited, because the new "page" they were given was simply the same page with new data.

All of those caveats make for a terrible user experience, and you never want to build sites that are a terrible user experience. I realize I just mentioned "JSON" twice, and I have not explained what a "JSON" file means. Don't worry. It's not important for now. In a future article, I will explain "JSON" files and I will elaborate more on the pitfalls of JavaScript. For now, let's just focus on the proper and sensible way to use JavaScript, and we'll address the poorly implemented uses later.

Having just derided using JavaScript to write content to a page, there can occasionally be a reason to use JavaScript in that manner. For example, if you have not learned a language like PHP, or your webhost only supports plain old HTML (not that I have ever seen a web host like that, but I'm just giving an example), you might want to write certain information with JavaScript, even though you might sacrifice some of your SEO rankings.

How do we start using JavaScript to write data on an HTML page?

JavaScript is a lot like CSS in that it can be applied to an HTML document in the same ways: Inline, Embedded or Linked.

We are going to start with some super easy JavaScript examples. Remember within the depth and breadth of JavaScript, there are literally THOUSANDS of things which JavaScript is capable of doing. JavaScript gives you a LOT of Legos to play with. We're just scratching the surface here. But, if I teach some basic syntax, and you see how JavaScript code is placed on a page, it will make it far easier to understand implementing things when you research more complicated stuff on your own.

PART 13 - LESSON A - JAVASCRIPT BASICS

<html> <head> <title>HTML for Non-Programmers</title> </head> <body> Be sure to "View Source" on this page, and read the comments, if you really want to understand it... <br><br> <!-- The line of code below is writing JavaScript directly on the page. Note how we OPEN and CLOSE the code using <script> very similar to how we OPEN and CLOSE embeded CSS with a <style> line. Inside our script, we use "document.write" to state that we will be writing some text in the HTML document. Then we use the parenthesis and quotes to enclose the text and we're all done! Pretty simple, huh? --> <script> document.write('This line is written by JavaScript embeded in the HTML page.'); </script> <p> <!-- The line of code below is importing our JavaScript file. Note that it looks very similar to the way we import a CSS file. Aso, just like a CSS file, this line of code is ALWAYS placed at the top of the page, but for this example, we're putting it down here just so the page reads a bit more logically for the class. --> <script src="includes/javascript-example.js" type="text/javascript"></script> <p> <!-- The lines below call the FUNCTION which is created in the JavaScript file. --> <script> writerThingyIsHere(); </script> <p> <!-- The lines below write the VAR which is created in the JavaScript file. --> <script> document.write(theLineOfTextToUse); </script> <p> <!-- The lines below write a table to the page, using a FUNCTION which is created in the JavaScript file. --> <script>buildingATableWithJavaScript();</script> <p> </body> </html>

Another example, of a more practical use of JavaScript, is at the very top of this page, doing the image-swap mouseover for the video player. Here is how that works:

PART 13 - LESSON B - JAVASCRIPT MOUSEOVER

<html> <head> <title>HTML for Non-Programmers</title> </head> <body> <!-- How is this working? In essence, we are making a DIV with a background image ("coming-soon.jpg"), and there is a transparent image ("1x1.gif") laid on top of it. When the cursor moves over the transparent image, we change the transparent images to the image of a player button ("play-button.png") When the mouse moves off the image of the player button, it swaps back with the transparent image again. The JavaScript is inline JavaScript and is just two attributes in the A HREF link - the "onmouseover" and "onmouseout" commands... You'll also notice, the image has a "name" attribute (horsepoopy) which is referenced by the JavaScript, so the JavaScript know which object is being changed. Pretty simple stuff. --> <div style="background-image:url('images/coming-soon.jpg'); background-repeat: no-repeat;"> <a href="https://www.youtube.com/watch?v=jEc_YOla4-0" onmouseover="document.horsepoopy.src='images/play-button.png'" onmouseout="document.horsepoopy.src='images/1x1.gif'" target="_blank"> <img name="horsepoopy" src="images/1x1.gif" style="width: 320px; height: 180px;"> </a> </div> </body> </html>

Finally, we will look at a page which uses JavaScript the way it SHOULD be used. But, if this is your first time taking this training, skip this lesson for now. Why? Because it uses concepts I haven't taught you yet, namely, webforms. What are webforms? Well, I teach those in 2 more chapters. See, I messed up. I didn't create these lessons in the same order that you are watching them. And, in all honesty, I forgot the lesson on webforms doesn't come for 2 more chapters. So, once you have learned webforms in Part 15, you can come back and check out this JavaScript calculator:

PART 13 - LESSON C - JAVASCRIPT CALCULATOR

<html> <head> <!-- First we link to our external JavaScript file. The JavaScript file contains all of the functions which will be called in the form. --> <script type="text/javascript" src="includes/calculator.js"></script> </head> <body> <h1>Online Bakery</h1> This page represents the proper way to use JavaScript - interacting with a webpage in real-time, and having data on the page change, based upon your selections. <br> As you make different selections in this form, pay attention to the "TOTAL PRICE" field at the bottom, and note how it changes. <br> When I say JavaScript should never be used to simply DISPLAY information, it should only be used to for INTERACTIVE data, this is what I am talking about. <br> <br> <!-- The form needs an ID associated with it, so the JavaScript will know what object on the page to interact with. We are calling this "orderform" as a variable ID name. We don't want the SUBMIT button to actually send anything, so we include the "return false" in an ONSUBMIT element. --> <form action="" id="orderform" onsubmit="return false;"> <div> <!-- These RADIO BUTTONS all have the same name. As a result, you can only select one at a time. The ONCLICK calls a JavaScript function, so the total will be displayed. --> <input type="radio" name="selectedpie" value="Round6" onclick="calculateTotal()">Pie 6" ($20) <br> <input type="radio" name="selectedpie" value="Round8" onclick="calculateTotal()">Pie 8" ($25) <br> <input type="radio" name="selectedpie" value="Round10" onclick="calculateTotal()">Pie 10" ($35) <br> <input type="radio" name="selectedpie" value="Round12" onclick="calculateTotal()">Pie 12" ($75) <br> <br> <!-- This is a DROPDOWN LIST. Note it calls the JavaScript function with a command called ONCHANGE whereas other elements of the form use ONCLICK. --> <select id="filling" name="filling" onchange="calculateTotal()"> <option value="None">Select Pie Filling</option> <option value="Lemon">Lemon($5)</option> <option value="Custard">Custard($6)</option> <option value="Fudge">Fudge($7)</option> <option value="Mocha">Mocha($8)</option> <option value="Raspberry">Raspberry($10)</option> </select> <br> <br> <!-- This is a CHECKBOX form field. Unlike a RADIO BUTTON, you can select multiple CHECKBOXES in a single form. --> Add some candles ($5)<input type="checkbox" id="includecandles" name="includecandles" onclick="calculateTotal()"> <br> <br> <!-- This is a CHECKBOX form field. Unlike a RADIO BUTTON, you can select multiple CHECKBOXES in a single form. --> Add some balloons ($20)<input type="checkbox" id="includeballoons" name="includeballoons" onclick="calculateTotal()"> <br> <br> <!-- This is where our total is displayed. --> TOTAL PRICE: <input type="text" id="totalPrice"> <br> <br> </div> <!-- Note this ONCLICK function attached to the SUMBIT button is not really necessary, since the form calls the ONCLICK function on every form field already. --> <input type="submit" id="submit" value="SUBMIT" onclick="calculateTotal()"> </form> </body> </html>

You know what you just accomplished? You just learned a fourth programming language, and you didn't even know it!

What am I talking about?

I'm talking about DHTML which is an abbreviation for "Dynamic HTML". You will sometimes see computer nerds throw around the term DHTML as if it's a unique language or something special.

Nope.

Once again, that is just stupid computer nerds trying to make you think they are smart. DHTML is nothing but HTML, CSS and JavaScript all being used together. If you build a page with HTML, CSS and JavaScript, you are using DHTML.

I know.

It's stupid. But computer nerds like to make things confusing and complicated.

Once upon a time, JavaScript was pretty lame. It was really complicated, couldn't do very much, and broke most browsers. Using JavaScript was a pointless waste of time. (Of course, the computer-nerds loved it.)

Over the years, that has changed significantly. JavaScript eventually became awesome. Suddenly, it was worthwhile to learn! JavaScript has transformed into a very compelling technology for adding functionality to HTML (way more powerful than CSS in fact). Although, regrettably, JavaScript is often used foolishly. For example, I once saw a developer use an entire line of intricate JavaScript code to open a link in a new browser window... a function attainable using TWO WORDS (target="_blank") in plain old HTML! Perfect example of a computer-nerd adding complicated technology for no good reason.

Don't do that.

Now that you understand why you should never use something like JavaScript to write text to your webpage, is there ever a time you should? Why would you want to use JavaScript to write text to your page? What possible advantage is there?

Well, on a single page, there isn't any advantage at all. But, suppose you are running a small business and you build a website with 20 pages. Suppose you actually want customers to contact you, so you wisely place your address and phone number on the footer of every page. What if your phone number changes?

If your phone number is hardcoded onto every individual page, you have to change your phone number on all 20 pages. But, if your phone number was being written dynamically out of a JavaScript variable... you see where I'm going with this?

Put your address in a JavaScript variable and you only need to change your phone number in ONE place and it will automatically change on all 20 pages of your site! Now that is a cool, practical and powerful use of some simple JavaScript!

BUT WAIT! THERE'S MORE!

You get the code! You get the example! BUT THAT'S NOT ALL!

Like a Ginsu Knife, it slices, it dices, and JavaScript can do a whole lot more! Write code to your page. Run clocks. Build a calculator. Open pop-up windows. Parse querystrings (you have no idea what that means, but trust me, it's pretty neato). One fellow even built an exact replica of the entire Lemmings videogame, purely in JavaScript. Check it out. Pretty amazing.

These "document.write" examples are just the beginning, but they are a really good start to illustrate an actual, practical use for JavaScript right off the bat. Used properly, JavaScript might even be able to saw through an aluminum Coke can... and STILL slice a tomato with ease!

All this can be yours for three low monthly payments of $19.95! Call now! Operators are standing by!

And remember, kids, the world owes you nothing... until you create things of value.


Glossary

DHTML

An abbreviation for "Dynamic HTML", which sounds like a new programming language, but it is nothing more than HTML, CSS and JavaScript all being used together. If you build a webpage utilizing HTML, CSS and JavaScript, you are using DHTML.

DOM

An acronym for "Document Object Model" and it describes the way a browser has been programmed to render HTML elements of a webpage.

javascript

Powerful and varied scripting language which allows a developer to manipulate the DOM.


Downloads


Other Articles