Let’s Learn JavaScript • Lesson 3 • Beginning JavaScript

ūüďÖ July 19, 2017
Continuing from the exciting Greetings Universe! HTML file we wrote in the previous lesson, let’s add some JavaScript to show a popup dialog and write text to the page.

 

 Overview

  • Adding JavaScript
  • When Does JavaScript Execute?
  • Writing Text to a Page
  • JavaScript and Case
  • Where is the Error?
  • Developer Tools
  • Writing to the Console
  • External JavaScript
    • Only JavaScript Allowed
    • Relative Path
    • Vivaldi Test
    • Firefox Test
    • Chromium Test
  • Browser Discrepancies

We will use this simple HTML 5 to write a simple JavaScript program. Open your favorite text editor (do not use an IDE) and enter the markup shown. This example is using gedit with an overview map shown as light purple on the right. The HTML file is saved as index.htm.

index.htm shown in the Vivaldi browser.

Adding JavaScript

Let’s add some simple JavaScript that will display a popup. Add the following script section within the body¬†of index.htm.

<!DOCTYPE html>
<html>
<head>
  <title>Greetings, Universe!</title>
  <meta charset="utf-8">
</head>

<body>
<h1>Greetings, Universe!</h1>

< script>
alert('This is a test using JavaScript.');
< /script>

</body>
</html>

NOTE: For this tutorial, remove the space between the < and script>. This is for display purposes on this page due to WordPress limitations. Actual tags do not contain the whitespace.

 

Enter

alert('This is a test using JavaScript.');

after the h1 element. Refresh or reopen index.htm in a browser and observe the result. (F5 is a keyboard shortcut that refreshes the current page.)

It’s a popup! Noooooo! Are we learning JavaScript just to do….this?

Firefox displaying the same index.htm file. Firefox dims the browser window when a modal dialog, such as alert, appears.

We use the script element to place JavaScript in a web page.

All content between the opening < script> tag and the closing < /script> tag is treated as JavaScript code by default, not HTML. Other scripting languages are allowed, but JavaScript is considered the standard.

< script>  Start of JavaScript code
< /script> End of JavaScript code

alert() is a JavaScript method that displays what is called a modal dialog box. Modal means focus is given exclusively to that dialog, and the user must respond in some way before proceeding.

The text ‘This is a test using JavaScript.’ surrounded by quotes within the parentheses is called a string, and it appears inside the popup. The user must click the OK button before the browser continues.

“What does¬†JavaScript from localhost mean?”

This is security mechanism to let the user know that the web page is generating the popup. Why? Because JavaScript has been around for a while, and it has been abused to trick users into clicking links, redirecting to malicious web sites, and otherwise perform some nasty surprises on unsuspecting users.

It is not fool-proof, but some warning is better than nothing at all. By informing the user that the popup is generated as a result of JavaScript being executed somewhere, it is less likely that a user will be fooled into calling a suspicious phone number that might appear in the popup.

In practice, popups of any kind are annoying because they are invasive and remove a user’s control over a web page in his own browser. The best advice is to avoid popups entirely.

When Does JavaScript Execute?

JavaScript code does not appear in the browser. The JavaScript interpreter immediately executes any JavaScript at the point encountered whether in the head or the body.

To see this in action, move the entire script ABOVE the h1 text as shown:

<!DOCTYPE html>
<html>
<head>
 <title>Greetings, Universe!</title>
 <meta charset="utf-8">
</head>

<body>

< script>
alert('This is a test using JavaScript.');
< /script>

<h1>Greetings, Universe!</h1>

</body>
</html>

Close the current tab if it is already open or open a new tab. Load index.htm again. The alert box will display BEFORE the header text appears.

Since JavaScript is encountered before the header, the popup appears first.

After clicking OK, the popup disappears and the browser continues rendering the page. The header text is shown.

Firefox also displays the popup before showing the header.

A browser executes JavaScript where found.

This is important because JavaScript can manipulate HTML elements on the page. If you try to access HTML elements before they exist, then your page might display with errors (varies by browser).

 

Writing Text to a Page

The alert() method displays a popup. What if we want to add text not found in the HTML? JavaScript to the rescue! Delete the existing alert script section, and write a document.write statement in a script section below h1 as shown below.

<!DOCTYPE html>
<html>
<head>
 <title>Greetings, Universe!</title>
 <meta charset="utf-8">
</head>

<body>
<h1>Greetings, Universe!</h1>

< script>
document.write('This is a test using JavaScript.');
< /script>

</body>
</html>

Refresh the browser to see the phrase This is a test using JavaScript appear in the page itself, not in a popup dialog.

Oh, looky! Text made using JavaScript, not HTML.

Yes, the phrase This is a test using JavaScript exists in the same file as the other markup, but the difference is that it appears on the page as a result of calling the document.write() method, not by placing it within any HTML elements (except for script to denote the JavaScript code).

How is this useful? For static text, it is not that great, but for text that changes upon each refresh, this becomes a valuable technique. Take dates, for example. Suppose we want to show the current date upon each browser refresh.

In the same document.write line, replace everything within the parentheses with new Date() as shown.

<!DOCTYPE html>
<html>
<head>
 <title>Greetings, Universe!</title>
 <meta charset="utf-8">
</head>

<body>
<h1>Greetings, Universe!</h1>

< script>
document.write(new Date());
< /script>

</body>
</html>

Refresh the browser a few times and watch the date/time change.

The current date and time from your computer’s system clock is shown in the given format by default. The new Date()¬†code creates a date object containing the current date and time complete with a time zone and offset.

JavaScript and Case

“HTML is not case-sensitive, so what about JavaScript?”

JavaScript IS case-sensitive. alert() will work, but ALERT() will not. Treat everything within the script tags as case-sensitive because it belongs to JavaScript, not HTML, even if the two are present within the same HTML file.

As an example, document.write() and document.WRITE() are completely different in the eyes of JavaScript. document.write() is correct, but WRITE() in uppercase will throw an error and the script will not execute. Try it for yourself.

<!DOCTYPE html>
<html>
<head>
 <title>Greetings, Universe!</title>
 <meta charset="utf-8">
</head>

<body>
<h1>Greetings, Universe!</h1>

< script>
document.WRITE(new Date());
< /script>

</body>
</html>

 

What? No date? Why?

Where is the Error?

When JavaScript fails due to an error, the browser will display what it can and then quit. It looks like the page is fine. No flashing lights. No alarms. Nothing. Usually, the JavaScript code will halt at the error, but how do we know that an error has occurred?

Developer Tools

Most browsers include debugging tolls called Developer Tools. Some include them only as an addon or extension. These tools display errors along with a wealth of other information that you can use to evaluate the efficiency of your web page.

In Vivaldi, Go to Tools > Developer Tools to open the tools window. Or, use the keyboard shortcut Ctrl+Shift+I.

How to open Developer Tools in Vivaldi. Other browsers are similar.

Developer Tools windows opens to the right of the page begin displayed.

Click the Console tab located in the bar at the top of the developer tools. The console shows JavaScript results as the JavaScript interpreter processes scripts. Immediately, we see the reason: document.WRITE is not a function, and the error occurred on line 16 of the HTML file named index.htm.

Aha! As reported by the Developer Tools console, line 16 contains the error.

Blank lines are counted, but the invalid code should be within the script tags.

The line number and type of error will change as you modify code. The JavaScript console in Developer Tools should be the first place to look if your JavaScript does not perform as intended. Edit the line and refresh.

Code corrected and the page refreshed.

Usually, nothing appears in the console when JavaScript executes properly.

Tip: Always use the Developer Tools when writing and testing JavaScript code in a browser.

Writing to the Console

The console is useful beyond debugging (finding errors in a script). We can also write messages to it using console.log() in order to view custom status messages as a script executes. Add two console messages: One message before h1 header and another after it.

<!DOCTYPE html>
<html>
<head>
 <title>Greetings, Universe!</title>
 <meta charset="utf-8">
</head>

<body>

< script>
console.log('Before the header');
< /script>

<h1>Greetings, Universe!</h1>

< script>
console.log('Page end');
< /script>

</body>
</html>

Messages appear in the console. Useful for debugging points of code.

The console displays the messages in the order the JavaScript is executed in the HTML file. The console.log() line numbers are also shown.

Line 12 displayed the first console.log() message, and line 18 displayed the second.

If we use document.write() instead of console.log(), the messages appear in the browser window, not in the console.

<!DOCTYPE html>
<html>
<head>
  <title>Greetings, Universe!</title>
  <meta charset="utf-8">
</head>

<body>

< script>
console.log('Before the header');
< /script>

<h1>Greetings, Universe!</h1>

< script>
console.log('Page end');
< /script>

</body>
</html>

Same messages, but different location. The console remains blank because no console.log() statements exist and because there are no errors.

External JavaScript

Up to this point we have been using the script element to delimit JavaScript code within an HTML file. In practice, this is not good. Why? Because we are mixing code and markup in the same file. This makes a page difficult to edit as it grows in complexity and as pages increase in number.

If a group of pages, such as ten, require the same script, using , we would have to copy and paste the same code into each of the ten pages. If we need to correct errors (a process called debugging) or modify the code in any way, then we must edit the script found in every page. This is tedious and time-consuming.

A better strategy is to place the code in its own JavaScript file and let all pages access that one file to access the code. Any script changes can be made in one place, and all pages will be affected.

Create a new text file and name it myscript.js. Place this file in the same directory as the index.htm file that you have been using so far. We can name the JavaScript file to anything we like. Just make sure to follow the all lower-case guidelines, avoid special characters, and give the filename a .js extension.

Only JavaScript Allowed

There are no tags or any other HTML markup in an external JavaScript file (unless that markup is a part of the JavaScript output intended for display). Everything is viewed as pure code by the JavaScript interpreter. The .js file is the source code. Open myscript.js in a text editor, and add the following lines of code.

document.write('Greetings from beyond the galaxy!');
alert('Even aliens use popups!');

The myscript.js external JavaScript file contains only JavaScript code. No HTML markup.

JavaScript processes code line-by-line from top to bottom in the order encountered.

Return to index.htm and remove all JavaScript.

Basic index.htm contains no JavaScript.

If we refresh index.htm as it is, only Hello, Galaxy! will appear. We must tell index.htm where to find myscript.js in order to execute it.

We use the script element, but the opening and closing tags will be empty. Instead, we use the src attribute in the opening tag. Add this line below the h1 header in index.htm.

< script src="myscript.js">< /script>

The markup should look like this:

The src attribute specifies a JavaScript source file to load.

src is an HTML attribute. It is followed by an equals character and then a value enclosed within double quotes to form a property=”value” pair. With the script element, it means “Load the specified JavaScript file and execute it.”

Relative Path

The value within the double quotes is a path to the JavaScript file. Absolute paths and relative paths are allowed. The path may even be another URL, such as src=”h t t p://0.0.0.0/somedir/myscript.js”. (Only an example. This is not a valid URL.) A relative path is relative to the HTML file. In this case, myscript.js exists by itself, so the browser interprets it as a file located in the same directory as index.htm. It is relative to index.htm. This is why index.htm and myscript.js (for this example) must exist in the same directory.

So far, index.htm and myscript.js should look like this:

index.htm (left) contains only HTML 5 markup, and myscript.js (right) contains only JavaScript code. This technique separates the code from the content.

Save all changes in both files and reload index.htm in the browser. Try opening the same index.htm in different browsers. The expected behavior might surprise you!

Vivaldi

Vivaldi Part 1. With Vivaldi already open, open a new tab, and open index.htm. The popup appears first.

Vivaldi Part 2. After clicking OK in the popup, the page displays.

Vivaldi Part 3. Reloading the page causes the popup to appear first while the previous page still appears. After clicking OK, the page refreshes the text.

Firefox

Firefox browser. The page displays the text and then the popup in the order that we expect.

Chromium

Just like Vivaldi, the Chromium browser shows the popup…

…and then shows the text.

Browser Discrepancies

“Why is this happening?”

Recall that JavaScript executes code in the order that it is encounter. There are exceptions and variance among browsers. There is nothing wrong with the JavaScript code. In theory, the page should display text and then show the popup last.

Firefox rendered the page in the order as written, but Vivaldi and Chromium did not. They showed the popup first even though alert() was the last line in myscript.js. When JavaScript loads an external JavaScript file, it will immediately process it at that point during the page render.

However, you are at the mercy of the web browser and its JavaScript engine. Exactly how a browser chooses to render a web page is out of your hands. Despite your best coding efforts, the way a browser is designed affects how your page will look.

To explain why Vivaldi and Chromium showed the popup first while Firefox showed the popup last as written would require explaining how the browsers differ and how they are constructed — topics that enter another realm.

The point to keep in mind is that browsers might render parts of your page differently whether dealing with styles or scripts. There is no guarantee that a page’s appearance or behavior will be exactly the same in every single browser from different manufacturers.

What looks good in one browser, might appear so-so in another. Older browses might ignore features completely. Even modal dialogs appear different in different browsers, and there is no way to change this from within a web page.

“That is confusing and unreliable.”

Welcome to the world of web design. Web designers have struggled with browser discrepancies for years, and there is still no one-size-fits-all, write-once-run-the-same-everywhere solution.

“How can I make a page 100% compatible in all browsers?”

You can’t, but you can get very, very close. You can write a page — HTML, style, and code — so the result is almost identical in every modern browser. This requires hacks and workarounds — especially if you use a bizarre browser called Internet Explorer. Even then, there will still be differences.

The older the browser the worse the problem becomes. So pick a range of browsers to design for, and then fail gracefully for all others. To fail gracefully means to have a fallback plan or a minimal page result so users on older or incompatible browsers can still have some form of functionality to navigate your site.

For example, your fancy navigation menu bar might feature eye-catching, swirling cloud effects rendered using WebGL, but older browsers unable to render WebGL should display a list of plain, blue links instead.

Browsers are adhering to web standards better than before, but there is still room for improvement.

Moral of the story: Do the best you can, but do not expect 100% cross-browser perfection.

Conclusion

This covers what we need to know in order to use JavaScript and HTML together. All that remains is the journey into learning the JavaScript language.

Advertisements

,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: