Let’s Learn JavaScript • Lesson 3 • Beginning JavaScript

đź“… July 19, 2017
Continuing from the exciting Hello, Galaxy! 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

  • How to Add JavaScript
  • Order of Execution
  • Writing to the Page
  • JavaScript is Case-Sensitive
  • 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

A basic HTML 5 file. We will use this to demonstrate JavaScript, so open a text text editor and enter this markup. Save it as index.htm. Shown here is gedit with the GreenScreen theme. The yellow block to the right is the overview map — an indispensable feature for long files.

Vivaldi browser displaying the index.htm page.

How to Add JavaScript

We have a basic HTML 5 file. Let’s add some simple JavaScript. Within the body section of the basic HTML file we created, modify the file by adding the script section so it looks like this:

<!DOCTYPE html>
<html>
<head>
  <title>Title Goes Here</title>
  <meta charset="utf-8">
</head>

<body>
<h1>Hello, Galaxy!</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.

 

Place

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

after the h1 element. Refresh or reopen the same file in a browser and watch what happens. (Pressing F5 on the keyboard will refresh the page in most browsers.)

Vivaldi browser running the modified index.htm. Hello, Galaxy! appears in the page followed by a dialog generated by the browser. Different browsers will display the dialog in different ways.

The same index.htm file displayed using Firefox. The page is dimmed while the dialog appears in the center of the page.

To place JavaScript in a web page, we use the script element. Everything between the opening < script> tag and the closing < /script> tag is considered to be JavaScript code by default. is part of HTML that says, “Here is the beginning of the script. Everything that follows is code.”  is an HTML tag that says, “Okay, we are finished with the code. Let’s return to HTML now.” 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 function that displays a modal dialog box. The text string surrounded by quotes contained within the parentheses is displayed in the dialog box. With alert(), the user must click the OK button before the page continues it actions. Modal dialogs behave like this.

“What is JavaScript from localhost?”

To notify the user that JavaScript is generating the dialog from code executed on the web page, the browser automatically adds some form of text to the dialog so the user knows where the dialog originates.

In the past, JavaScript has been abused to generate dialogs similar to operating system dialogs (namely, Windows) in order to trick users. To reduce the chances of trickery, some modern browsers disclose JavaScript actions. Firefox, as seen in the picture above, only displays the text.

This is supposed to help protect you from tricks and rotten scare tactics, but it can still be abused to annoy users. Use it sparingly, or, better yet, avoid using it completely.

Order of Execution

JavaScript code is not displayed in the browser. The JavaScript interpreter executes the JavaScript immediately at the point encountered on the page during rendering. When the JavaScript code completes its execution, the browser returns to HTML rendering.

To test this, place the script section ABOVE the h1 text like this:

<!DOCTYPE html>
<html>
<head>
 <title>Title Goes Here</title>
 <meta charset="utf-8">
</head>

<body>

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

<h1>Hello,Galaxy!</h1>

</body>
</html>

Open a new tab or close the existing page to see the effect. Refresh the page, and you should see the alert box display BEFORE showing the h1 text.

In Vivaldi, you must open a new tab before refreshing or else you will see the old page while the dialog from the new page loads. It will not look like there has been any change.

The dialog disappears after clicking OK. The page text is displayed because it is listed after the JavaScript code in the page.

Here is Firefox showing the same file. The dialog appears before any text.

JavaScript is executed in the order it is encountered. This is an important concept to understand because JavaScript manipulates HTML elements. If you try to access HTML elements before they exist, then the browser will throw errors and the page might not display properly (depending upon the browser).

 

Writing to the Page

We can use JavaScript to write text to the page that is not contained in the markup. Move the script element below the h1 header element and replace the alert with a document.write as shown below.

<!DOCTYPE html>
<html>
<head>
 <title>Title Goes Here</title>
 <meta charset="utf-8">
</head>

<body>
<h1>Hello, Galaxy!</h1>

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

</body>
</html>

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

The text below Hello, Galaxy! is produced using JavaScript, not HTML.

We could have written this text directly in the markup, but what if the text changes upon each refresh? Let’s try showing the current date to see dynamic text in action. In the document.write line, replace everything in the parentheses with new Date() as shown below.

<!DOCTYPE html>
<html>
<head>
 <title>Title Goes Here</title>
 <meta charset="utf-8">
</head>

<body>
<h1>Hello, Galaxy!</h1>

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

</body>
</html>

Showing the current date and time in a page using JavaScript.

This displays the current date obtained from your computer’s system time. Each time you refresh the browser, the time will update (usually the seconds).

new Date() creates a date object that can then be used to grab specific parts of the date for manipulation and display. Handling dates, time zones, and time conversions is a lengthy topic, but for now, new Date() will grab the date quickly and easily.

JavaScript is Case Sensitive

“Does case matter?” Yes.

HTML is not case sensitive, but JavaScript is. When the browser reads the HTML, it does not care if it sees <html> or <HTML>, for example. But when the browser reaches the code, the JavaScript interpreter expects to see source code written in the correct case.

document.write() and document.WRITE() are seen as two different things by the JavaScript interpreter. The first is correct, but the second is wrong, and it will throw an error. The JavaScript will not execute.

<!DOCTYPE html>
<html>
<head>
 <title>Title Goes Here</title>
 <meta charset="utf-8">
</head>

<body>
<h1>Hello, Galaxy!</h1>

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

</body>
</html>

 

Hmm…No date.

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.

At the top of the developer window, click the Console tab. This shows JavaScript results as the page executes JavaScript. Immediately, we see the reason: document.WRITE is not a function, and the error occurred on line 17 of the HTML file named index.htm.

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

Blank lines are counted, but the invalid code should be within 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 have the Developer Tools open when writing and testing JavaScript code in a browser.

Writing to the Console

We can do more than observe errors in the JavaScript console. We can write messages to it using console.log(). Let’s add two console messages. One before the h1 header and another after.

<!DOCTYPE html>
<html>
<head>
 <title>Title Goes Here</title>
 <meta charset="utf-8">
</head>

<body>

< script>
console.log('Showing content');
< /script>

<h1>Hello, Galaxy!</h1>

< script>
console.log('All done');
< /script>

</body>
</html>

Writing to the console.

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

The first console.log() was encountered in index.htm at line 11, and the second at line 17.

You can write debugging messages to the console at different parts of your code to view status information or your making.

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

<!DOCTYPE html>
<html>
<head>
 <title>Title Goes Here</title>
 <meta charset="utf-8">
</head>

<body>

< script>
document.write('Showing content');
< /script>

<h1>Hello, Galaxy!</h1>

< script>
document.write('All done');
< /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: