The Console

You'll find that the console is an invaluable tool in authoring JavaScript for its ability to give the web developer feedback without the developer having to implement code that might disrupt the use of the site for normal users.

In both Google Chrome and Mozilla Firefox you can open the developer tools by pressing the "F12" button on your keyboard. At this time the Microsoft browser is not suitable for debugging web pages.

In both cases, once the console is open, you may need to click the "Console" tab at the top of the deb tools to make the Console visible. At first it will be a blank screen but if you were to load (or reload) a page (most popular web pages will do) while the console is open then you should be able to see various messages and/or warnings that the browser might encounter upon a page load.

Console commands

Let's look at some forms of console commands

console.log()

There is one method that all JavaScript authors absolutely must learn. Well there are many "musts", but one important one is "console.log()". Essentially this will allow you to output any data as plain text to the console window. This is useful in that it can give you information about your page that may not otherwise be measureable. This may be anything since, for the most part, web pages don't ever display thier raw code for the client to view.

For instance if you are making an image fade in and out but you are experiencing a problem where the image is only fading part way you can use "console.log()" to find exactly where the animation stops, and if used right, find out which part of your code is and is not running.

console.table()

While we haven't gone over how JavaScript objects / lists work yet there is also another form of console logging that may be helpful once you do start using them. Feel free to return to this point later as a refresher once you are comfortable with objects / lists.


// If you want to try it for yourself, it is very easy to do.

// First write some JavaScript.  More complex lists and objects
// will make the difference more apparent than simple data.

// If want, copy and paste the following code to a blank
// html file, open the inspector, and hit refresh.

var console_output_variable = 12345;
var console_output_object = [
    { name: "Bobby", flavor: "Strawberry" },
    { name: "Jenny", flavor: "Mocha" },
    { name: "Knute", flavor: "Optimistic" }
]

console.log( console_output_variable );
console.log( console_output_object );

console.table( console_output_variable );
console.table( console_output_object );

// With this code you'll notice the output within the console
// has changed to resemble the following image.

You'll notice two things about the use of the "table" method.

1. It either does not change, or does not even display, the basic data type. Simple number or string entries are not sets of data and therefore are not really meant for "table".

2. The list or object data that you've written will be shown in a much more visually pleasing matter with clearly labeled elements.

Web developer Jilles Soeters has a good write up of this and other console commands that you can make use of at the following link.

Chrome Console APIs you’re probably not using yet

Error catching

One somewhat frustrating quality of JavaScript is the way in which it handles errors. It's inevitable that during programming errors will appear either due to mistakes of the coder or incompatibilities between browsers.

As you might have noticed, if you've already tried some original code, even the slightest error in JavaScript code can bring the entire program to a stop. This is because there are no built in "fail safes" or alternate actions for browsers to take upon detection of such errors.

Any given web browser will cease to read script the moment a single error is detected.

This actually makes perfect sense as most programs are completely dependent on themselves. If a program built to manipulate an array of buttons can't find the name of the array it has been asked to look for then it doesn't matter if the buttons actually exist or not. How can it manipulate the buttons if it can't find the list they are referenced in? The ability of any given function to work properly is dependent on previous functions and properties doing their job just the same.

Detecting disabled JavaScript

During the early years of JavaScript it was sometimes seen as a security risk. Because of that many browsers began offering the option of disabling it or even defaulting to it not being enabled. Thanks to increases in browser security over the years this is less of a concern.

This does not mean there are not other reasons that a client might not be able to utilize JavaScript. Users in sensitive environments might have it disabled (government computers). A client might be having technical problems that make running JavaScript contribute to response slow down. They may be on a type of mobile device that doesn't support it.

So to ensure compatibility in those cases, unless we deem our JavaScript minimal enough to just scrap, we need to test for whether or not a user can utilize JavaScript. This is simple enough with the "<noscript>" element tags. Placing these tags around anything within your document will make it so that the enclosed markup / code will not run unless the user has their web browser set to *not* run JavaScript.



<html>
<body>
<style>

#example_box {
	background-color: pink;
    padding:10px;
    outline:1px solid black;
}

</style>

<div id="example_box">
This is my div, there are many like it, but this one is mine.
</div>

<!-- Here we've put our "noscript" element.  Anything within it will only be
considered by the browser if JavaScript is turned off. -->

<noscript>

<style>
#example_box {
	background-color: lightgreen;
}
</style>

</noscript>

</body>
</html>
<script>

// Now I can't force your browser to turn off JavaScript so you'll just have to
// image the effect of the following line in which we set the background color 
// of the box to 

document.getElementById('example_box').style.backgroundColor = "lightblue";

// Normally this code would change the background color of the box to blue, but
// if you have javascript turned off then the div "example_box" will appear as 
// green.

</script>

This is my div, there are many like it, but this one is mine.

There are many things you might want to account for besides simple background color changes.

  • Menus that have animated buttons may need ":hover" selection code to fall back on.
  • Galleries that are made procedurally may need a default icon to show where the image link can be clicked if the animated gallery selection can not occur.
  • Audio or Video files that can not be manipulated by JavaScript may need a message or image saying they are not available.

...and so on.

Waiting For Page Loading

Note: Some parts of this section may not entirely make sense until you've studied further sections. You may want to remind yourself to come back later at some point.

One issue with JavaScript development on web pages is something that may not come up until later on in the development of a complex site, but is best to be aware of early on, is the question of how JavaScript interacts with assets that need to be downlaoded / loaded into memory.

This is a scenerio that is difficult to show with a coding example because it is dependent on the hardware and software configuration of the client computer. Since we are all on different computers it may not always work the same way..

Let's remind ourselves of the order of operations when you browse to any given web page.

  1. The computer reads the HTML DOM.
  2. The computer begins downloading any links within the HTML to assets such as images, sound clips, or other links.
  3. The computer reads the SCRIPT associated with the HTML that is most often set to run at the end of the HTML DOM.
  4. The computer begins to enact the script regardless of whether or not step 2 has completed.

At this point if the client computer has not finished retrieving the page assets and a script tries to use or change that unloaded asset then unexpected results will occur. This can range form anywhere between the code throwing an error and stopping altogether or the code simply not doing anything at all.

Since the result can vary so much, depending on what is found by your script and what isn't, it can be very difficult to troubleshoot / debug such a problem. The simple way to adapt to this situation is to force the JavaScript code to wait for all of the assets related to the page to be loaded. This can be done with a single line.


window.onLoad = function(){ //code };

As you can see the onLoad function is not phrased exactly like other functions. This is because it is a default function of JavaScript. It is using an anonymous funtion called on a default listener type to run code of your choosing.

Let's look at this line in the context of an actual web page.



<html>
<style>
</style>
<body>

<audio id="audio_element">
	<source src="example.mp3" type="audio/mpeg">
</audio>

</body>
</html>
<script>

// Within the HTML we have an "audio" element, it contains a link to
// the source for the audio ("example.mp3") and an id attribute for
// referencing within JavaScript.

// In JavaScript we make a reference to an element by the method 
// "getElementById".
var audio = document.getElementById("audio_element");

// Once that reference is made JavaScript can actually play the audio clip on
// command fairly easily.  You just invoke the "play" method that will start
// playnig any recognized media format.
audio.play();

// The above line may not work though.  Since this script section is run 
// immediately after the HTML section is read, the actual file the audio element
// is linked to may not yet be fully loaded.

// Here we try the onLoad function.  Asy you can see it uses an inherent
// property governed by the browser to know when it can run the code.

window.onLoad = function(){

	// Write you entry point code here.
    // This could include event listeners and "setinterval" methods.
    
    // Or any code that might manipulate loaded assets, like so...
    
    // Here we try and enact a "play" command" on the audio object linked to 
    // within the HTML body.  Since everything within "onLoad" has waited until 
    // the contents of the page have loaded to start working, this line of code 
    // has a much better chance of actually running that the previous play 
    // command did.
    audio.play();
    
}

</script>

As stated this is a difficult concept to convey through an actual example. You'll just have to trust me for now!