Search

JavaScript Coding & Development

  • Thread starter EmeraldHike
  • Start date
EmeraldHike

EmeraldHike

Member
Joined
May 10, 2021
Messages
133
Reaction Score
0
Points
21
  • #1

What is JavaScript?​

Technical people have got to be some of the most challenging types of folks to listen to while trying to learn about technical things. That’s a pretty big statement, but I think I’ve lived long enough to realize that it’s got some merit. I’m sure we can all remember back to high school or college when we had that very, very qualified teacher or professor. While they were teaching, you just couldn’t seem to grasp what they were talking about. And it seems that the smarter they were, the more of a challenge they had at getting their point across.

The Challenge​

I think the underlying issue with what I’m discussing here is that really technically oriented types gloss over important parts of what they’re conveying. And since we’re talking about JavaScript in this post, I’ll give you an example.

ME: Hey, I’m playing around and I want to get that annoying little box to pop up in my browser. How do I do that?

HIM: Just alert it from the console.

Do you see what I’m talking about? Let’s take a closer look at what just happened above. Obviously, I have zero experience in JavaScript and this is why I’m asking such a simple question. If I had taken even the most rudimentary of courses or tutorials on the subject, I would know what the “alert” command was. If I knew that much, I would possibly have some experience with the console. Now, since I don’t know what an “alert” is, I most certainly don’t know what the console is. The fact that the person I asked the question to couldn’t pick up on that is a good example of what I’ve alluded to above. It happens all the time and this is why I say that technical people make tough teachers to learn from. It’s either because they don’t have enough time to think about such trivial matters or they just don’t know how to get so basic anymore.

Let’s just say, there are a lot of assumptions flying around out there and in order to get good at something, we need to start at the beginning. The real beginning.

Some Credentials​

Before I go any further, I’m going to give you my credentials. Since I’m just starting out, you already know I’m no expert. I do have a pretty good idea of how to explain things though, especially to beginners.

So far, I’ve taken a few classes in JavaScript.

Treehouse

Introduction to Programming
JavaScript Basics
JavaScript Loops, Arrays and Objects
Interactive Web Pages with JavaScript
jQuery Basics
AJAX Basics

Lynda

Foundations of Programming: Fundamentals with Simon Allardice
JavaScript Essential Training with Simon Allardice
JavaScript for Web Designers with Joe Chellman

As you can see, I’ve had my fair share of opportunities to listen as someone explained to me exactly what JavaScript is. I must say, the instructors in these videos did a pretty good job. I now do know what JavaScript is. Not in a theoretical sense or anything, but I know what it is, what it does and what it’s capable of (Well, not really. That’s never ending.).

My Explanation​

What I’m going to do here is attempt to explain what JavaScript is in the most simple and basic way, then give you the typical explanation of what it is that you’ll read and hear a thousand times. After that, we’ll call it a day.

So, what is it? Well, most simply put, JavaScript is an assistive translational tool. You have a thought in your head and you want that thought to happen on the computer screen. Working from my example above, you want to see the annoying pop-up box – you just don’t know how to make it happen. You can’t wish it were there and you can’t make it appear by wagging your finger at it, but you can command the computer to show it to you while using a language it understands.

ME: Show up you little box!

COMPUTER: I really don’t know what you’re saying. I don’t even have ears. Perhaps if you asked me in a way I understood, we’d both be happier.

ME: Okay, fine. How about:

Code:
alert("Hello! I am an alert box!");

COMPUTER: Ah, now you’re speaking my language.

It’s like learning any language. As an English speaker, if I wanted to ask where the bathroom was and eventually go there while visiting France, I’d need to ask a French person in their language. I’d say something like, “Où sont les toilettes?” If I did that, I’d end up in the bathroom. If I simply said, “Where is the bathroom?”, I’d get a funny look. The same look the computer gave me when I begged it to pop up an alert box.

Again, JavaScript is an assistive translational tool. As is any programming language. Once you understand that fact while you’re programming in JavaScript – you’re simply translating your thoughts into computer-speak – you’ll have an easier time. Some of the fight will be gone. You’ll begin to accept what you’re doing. All you need to do is to learn exactly what that computer-speak is – that’s what all those classes out there are for. They teach you what to do.

Some More Formal Definitions​

As promised, I’m now going to go over some of the more popular definitions of what JavaScript is. I’ll pull a few definitions and then discuss them.

WikipediaJavaScript is a dynamic computer programming language. It is most commonly used as part of Web browsers, whose implementations allow client-side scripts to interact with the user, control the browser, communicate asynchronously, and alter the document content that is displayed.

W3SchoolsJavaScript is the programming language of HTML and the Web. Programming makes computers do what you want them to do.

Mozilla Developer NetworkJavaScript (often shortened to JS) is a lightweight, interpreted, object-oriented language with first-class functions, most known as the scripting language for Web pages, but used in many non-browser environments as well such as node.js or Apache CouchDB.

People out there like to say that “JavaScript is the programming language of the web” and that “JavaScript is object-oriented.” I think I like the second definition above when it says that “…programming makes computers do what you want them to do.” That one is pretty good. If I had to explain it to a third grader, that’s probably what I’d say. To further assist you in understanding the definitions of JavaScript above, I’m going to break down the key terms.

Key Terms​

Programming Language – A programming language is a formal constructed language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs to control the behavior of a machine or to express algorithms. (read more)

Dynamic Programming Language – You can read all about what makes a computer programming language dynamic versus what makes is static right here.

Interpreted Programming Language – An interpreted language is a programming language for which most of its implementations execute instructions directly, without previously compiling a program into machine-language instructions. The interpreter executes the program directly, translating each statement into a sequence of one or more subroutines already compiled into machine code. (read more)

Object-Oriented Programming Language (OOP) – Object-oriented programming (OOP) is a programming language model organized around objects rather than “actions” and data rather than logic. Historically, a program has been viewed as a logical procedure that takes input data, processes it, and produces output data. (read more)

Scripting Language – A scripting language or script language is a programming language that supports scripts, programs written for a special run-time environment that can interpret (rather than compile) and automate the execution of tasks that could alternatively be executed one-by-one by a human operator. (read more)

Wrapping It Up​

I think I’ve covered most bases here. I think the best thing about writing this type of thing out, for me anyway, is that I have to do research. Every time I look for a definition of something, I have to read it to make sure it fits into what I’m trying to convey. Each time I read it, I learn and that’s what it’s all about.

Do you have your own definition of what JavaScript is? Is it super-simple, sort of like what I described it as or is it much more thorough? If you have something, I’d love to hear what it is via the comment form below. Go ahead – show off what you know!
 
EmeraldHike

EmeraldHike

Member
Joined
May 10, 2021
Messages
133
Reaction Score
0
Points
21
  • #2

The Syntax of JavaScript​

Like any language, JavaScript needs to be written in a specific manner in order to be understood. There’s a certain “syntax” that’s required. And like any language, if the syntax gets sloppy or is written incorrectly, you end up with either inefficient code or even worse, code that doesn’t work.

In this post, I’m going to go over some of the syntax JavaScript uses. I’ll also discuss a few golden pieces of information you need to remember while coding in JavaScript.

Nuggets of Information​

First, JavaScript is an interpreted language, meaning its instructions are executed on the fly. They don’t need to be compiled into something else first, in order to operate.

Many of the languages you’ll write today are interpreted languages, so this isn’t something you really need to concern yourself with, especially if you’re like me, who is dabbling in some of the more popular web programming languages. It’s good to know though.

Next, JavaScript is case sensitive. It matters what case you code things in. For example:

Code:
var x = 5;
var y = 6;

is not the same as:

Code:
var X = 5;
var Y = 6;

Notice how I capitalized the “X” and the “Y” in the latter two variables. Since one set of variables is lowercase and the other is uppercase, they can be used in the same program, but will apply to different things. Also, if you’re using one of the built-in functions of JavaScript and you alter the case of the function, it will not work.

I mentioned this in my previous post about PHP and the idea is similar to the one in JavaScript – Many programming languages, such as JavaScript, use statements, which are instructions to be executed by the web browser. These statements do things and are obviously necessary.

JavaScript statements end in a semicolon. Here is an example of that:

Code:
a = 20;
b = 40;
c = a + b;

When it comes to whitespace, the same rules that I wrote about in my PHP post apply to JavaScript. And to go over them once more, I’ll tell you that JavaScript doesn’t care about whitespace in its statements, but it does within its strings. Here is an example of whitespace use in JavaScript:

Code:
var name = "My Name";

The above example is the same as this one below.

Code:
var name="My Name";

But, both of those examples are different than this one:

Code:
var name = "My    Name";

Notice the space usage around the equal sign in the first two examples and then in between my first and last name in the final example.

Commenting JavaScript is very similar to commenting in PHP. I’ll give you a few examples here:

Code:
// this is my name
var name = "My Name";

It’s common to comment directly above a statement. Or, in the example below, you can comment directly after a statement.

Code:
var name = "My Name"; // this is my name

Or, you can use multi-line comments.

Code:
/*
in the line
below, you will
see my name
*/
var name = "My Name";

Writing JavaScript​

When writing JavaScript, you can either write it inline, in between your HTML code or write it in an external file and call it into your HTML. Generally speaking, it’s standard practice you write your code in an external file, but there is some disagreement with that. I’m going to write some pros and cons for each method below.

Inline

– Reduces the number of HTTP requests because no extra file is called.
– Performance may be better if inline JavaScript is short.
– Easier to write inline if testing code.

Here is an example of inline JavaScript:

Code:
<script>
alert("My name is Tom.");
</script>

External

– Greater performance because external file can be easily cached by browsers.
– Easier to maintain because all JavaScript is in one file as opposed to the same code being spread out across multiple HTML files.
– Special characters in JavaScript can cause issues if run inline with HTML.
– If the same JavaScript runs across multiple HTML pages, you have duplicate code.

And here is how you would include a JavaScript file into an HTML page:

Code:
<script src="javascript-file.js"></script>

When including your external JavaScript file into your HTML page, you have a choice of whether to place your code at the top of the page or at the bottom. I remember years ago, all I would see is the inclusion of JavaScript at the top of the page, in the head section. Now though, I am seeing it at the bottom more and more. The reason for this is because of the way JavaScript code is parsed. If you include it at the top of the page, your JavaScript will run before the entire page is loaded. If there’s an error somewhere, your page won’t load at all. And as far as where you can place your script tags at the bottom – they generally go right above your closing body tag.

Variables​

JavaScript variables are simply containers for data. The way to define a variable is actually quite simple. Here’s an example of a variable:

Code:
var name;

Like PHP, there are a number of rules to follow when defining a variable. You can either follow this link to read more about JavaScript variables or read on below. I’ll list those rules here:

All JavaScript variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y), or more descriptive names (age, sum, totalVolume).

The general rules for constructing names for variables (unique identifiers) are:

– Names can contain letters, digits, underscores, and dollar signs.
– Names must begin with a letter.
– Names can also begin with $ and _ (underscore).
– Names are case sensitive (y and Y are different variables).
– Reserved words (like JavaScript keywords) cannot be used as names.

Identifying a variable by itself is simply reserving a space for data to reside. It’s only when you assign your variable a value is it equal to something. Otherwise, your variable is left undefined.

If you’d like to assign a value to your variable, you need to set it with an equal sign (the assignment operator). Please be aware that while this looks like the same equal sign that we’re all used to from math class, it isn’t. This equal sign assigns a value to a variable, it doesn’t make the value equal to the variable. Those are two very different things.

There are two ways to assign a value to a variable:

Code:
var name;
name = "Tom";

or

Code:
var name = "Tom";

In the first example above, I first defined the variable (reserving a space for data to reside) and then I set some data to it. In the second example, I defined the variable and set the value of “Tom” to it all in one line. Either way is fine, but the second is more common.

When setting data to variable, there are a few things to watch out for. First, you are allowed to set integers to a variable, such as:

Code:
var number = 200;

You are also allowed to set boolean (true or false) values to a variable, such as:

Code:
var question = true;
var question = false;

You may also set a string to a variable, such as:

Code:
var name = "Tom";
var name = 'Tom';

It is up to you whether or not you want to use single or double quotes when using a string. The rule is, don’t mix them. Choose one or the other.

Conditional Statements​

Asking questions using JavaScript can be fairly straightforward. If you’d like to know if one number is greater than another, you can do that. You can also discover whether one number is greater than or equal to another number. If you’d like one section of code to run if one condition is met, that’s cool – and if you’d like another section of code to run if that same condition isn’t met, that’s cool too.

Below, I’m going to discuss some conditional statements that you can use in JavaScript. If you’ve programmed at all, you’ve most likely heard of these, but if you haven’t, they aren’t too challenging to pick up on.

if Statement

This is, very simply put, a statement that allows a block of code to run if a condition is true.

Code:
if (condition) {
    code that is executed if condition is found to return a true value
}

I’ll give you an example of what it looks like:

Code:
if (age > 18) {
    response = "Wow, you are older than I am.";
}

In the code above, you’re asking if someone’s age is greater than 18 years. If it is, a response will be generated that says, “Wow, you are older than I am.” If their age is less than 18, nothing will happen because no code will be executed.

else Statement

Let’s say that, instead of nothing happening if someone’s age is not greater than 18, you wanted a response to be generated. In that case, you’d have to use the else statement.

Code:
if (condition) {
    code that is executed if condition is found to return a true value
} else {
    code that is executed if condition is found to return a false value
}

Here’s an example of what that looks like:

Code:
if (age > 18) {
    response = "Wow, you are older than I am.";
} else {
    response = "Wow, you are the same age or younger than I am.";
}

Now, if the person’s age is anything other than greater than 18, a response will be generated that says, “Wow, you are the same age or younger than I am.”

else if Statement

Here’s a question – What if the person’s age is equal to 18 and you wanted to generate a response for just that? In the examples above, the first generated response was returned only if the age was greater than 18. The second generated response would return if the age was less than or equal to 18. We have yet to program the ability to generate a response for the age being equal to 18 years.

In order to generate a response for a third condition, we’ll need to use the else if statement.

Code:
if (condition) {
    code that is executed if the first condition is found to return a true value
} else if {
    code that is executed if the first condition is found to return a false value and the second condition is found to return a true value
} else {
    code that is executed if both the first and second conditions are found to return false values
}

Here’s a simple example of an else if statement, building off the first two examples:

Code:
if (age > 18) {
    response = "Wow, you are older than I am.";
} else if (age < 18) {
    response = "Wow, you are younger than I am.";
} else {
    response = "Hey, we are the same age!";
}

Now, if someone’s age is the same as ours, a response will be generated that says, “Hey, we are the same age!”

Operators​

Operator are the tools, or symbols, we use to manipulate values in JavaScript. The values we use operators to manipulate are called operands. An easy example of an operator is the plus (+) symbol. This symbol will add two operands together. Another easy one might be the less than (<) symbol. This symbol performs a check to see if the value of the left operand is less than that of the right. JavaScript supports many types of operators. I'll link to a few websites that have excellent pages that go into decent depth regarding JavaScript operators. - JavaScript Operators at W3Schools

JavaScript Operators at Tutorials Point

The reason I link to the above sites is because they’ve already compiled everything I would have written here. I actually began writing it and then discovered that I would have been duplicating everything they already have.

Besides simply being aware of the existence of JavaScript operators, you also need to be aware of the precedence they follow in relation to each other.

Code:
result = 5 + 5 * 10;

In the example above, the multiplication operator takes precedence over the addition operator, so, in this case, the numbers 5 and 10 will be multiplied before the first 5 will be added to anything. A nice reference for operator precedence can be found here. by the way, the above result is 55.

Now, if you wanted to add the two 5 values together before the 10 was multiplied like it was above, you would add parenthesis around the addition operands.

Code:
result = (5 + 5) * 10;

This would change the order of operations and give you a result of 100.

Loops​

In JavaScript, a loop can execute a block of code a number of times. This is especially helpful when there is something you need automated, such as a counter or when you’re working with arrays. In order to create loops, you’ll need to utilize a variety of statements. These statements are the driving force behind loops and are:

for – loops through a block of code a number of times (reference)
for/in – loops through the properties of an object (reference)
while – loops through a block of code while a specified condition is true (reference)
do/while – also loops through a block of code while a specified condition is true (reference)

I’ll go over each type of loop and then give an example of each.

for Loop

You can include three expressions in this loop. They are enclosed in parentheses and separated by semicolons (;). The expressions are followed by a code block that includes a statement or statements to run.

Code:
for ([initialization]; [condition]; [final-expression])
   statement
for (var i = 0; i < 9; i++) {
   console.log(i);
}

for/in Loop

This loop iterates over the enumerable properties of an object, in random order. For each distinct property, statements can be executed.

Code:
for (variable in object) {...
}
var obj = {a:1, b:2, c:3};
  
for (var prop in obj) {
  console.log("o." + prop + " = " + obj[prop]);
}
 
// Output:
// "o.a = 1"
// "o.b = 2"
// "o.c = 3"

while Loop

Creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before the loop is run.

Code:
while (condition) {
  statement
}
var n = 0;
var x = 0;
 
while (n < 3) {
  n++;
  x += n;
}

do-while Loop

This loop executes a statement until the condition it’s looping returns a false value. The loop has to occur at least once for the condition to be evaluated.

Code:
do
   statement
while (condition);
var i = 0;
do {
   i += 1;
   console.log(i);
} while (i < 5);

Beyond the statements I explained above, there are two others that are worth mentioning. They are break and continue.

break – jumps out of a loop (reference)

continue – jumps over one iteration in the loop (reference)

break

Code:
for (i = 0; i < 10; i++) {
    if (i === 3) { break; }
    text += "The number is " + i + "<br>";
}

continue

Code:
for (i = 0; i < 10; i++) {
    if (i === 3) { continue; }
    text += "The number is " + i + "<br>";
}

Functions​

The final area of JavaScript I’m going to discuss today is functions, which are a series of statements that have been grouped together to perform a specific task. When you call a function, you execute it.

I’m going to give you an example of what a function looks like and then I’ll go through its parts.

Code:
function exampleFunction (number1, number2) {
    return number1 + number2;
}

In the above example, “exampleFunction” is the name of the function. When naming a function, there are some rules to follow. Luckily, the rules are the same as when naming variables, so if you’re interested in what those are, please see the top of this post.

The parts of a function are the “function” keyword, then the name (exampleFunction), the two parentheses. Within these parenthesis, you can hold parameters (number1, number2). Those parameters are separated by a comma. Lastly, the code you’d like to run is placed within two curly braces. In the case of the example above, the code we would like to execute is “return number1 + number2;.”

Now, it’s important to remember that functions don’t need to have data passed into them. You can keep those parenthesis empty, unlike the example above. If you create your function this way, it’ll simply run without any arguments.

Let’s say we have a similar function to the one above, but we don’t have any parameters. It’ll look something like this:

Code:
function exampleFunction () {
    // code i'd like to run
}

By itself, this function wouldn’t do anything. It’s not until you call it that it would execute the code inside it. To call a function, you use its name, the parenthesis and end your line with a semicolon.

Code:
exampleFunction ();

If we did want to pass in the parameters to make the first example work, we would call it like this:

Code:
exampleFunction ( 2, 5 );

The output of that first function when called with those arguments would be “7.” All we’re doing is saying, “I’m giving you the parameters you are asking for as arguments in a function call and you are running the function code block and giving me back the result.
 
EmeraldHike

EmeraldHike

Member
Joined
May 10, 2021
Messages
133
Reaction Score
0
Points
21
  • #3

JavaScript Types & Objects​

If you’re interested in JavaScript types and objects, you’re in the right place.

Arrays​

In order to learn about arrays, it might be wise to first get familiar with JavaScript variables, as they are very similar in their construction. While variables hold one value, arrays are able to hold multiple values. This is part of the reason arrays are so powerful when programming in JavaScript.

To get the ball rolling here, I’ll give you an example of a variable:

Code:
var sampleVariable;
sampleVariable = 100;

or

Code:
var sampleVariable = 100;

Now, I’ll give you an example of an array:

Code:
var sampleArray = [];

Notice the square brackets in the array example. That’s what tells you that you’ve got an array. It’s called an “Array Literal.”

If you want your array to hold values, you need to tell it what you want. In order to do that, you would specify the key and then the value right after that.

Code:
var sampleArray[0] = "&quot;"car";

You can also add additional values by specifying one for each key that follows:

Code:
var sampleArray[0] = "car";
var sampleArray[1] = "bus";
var sampleArray[2] = "train";

It’s important to remember, it’s up to you which data type you’d like to use in your arrays. I chose to include strings, but feel free to use integers, booleans, etc… Also remember that arrays use a zero based index, so your first value will have a key of 0.

If you want to display the output of a particular value in an array, you would write code that looks like this:

Code:
console.log(sampleArray[1]);

And your output would be this:

bus

Arrays in Shorthand

In the examples I gave above, the method the arrays were written in was longhand. There is a shorthand method to write these in and that would look like this:

Code:
var sampleArray = ["car", "bus", "train"];

If you’ll notice, we only had to name the array once, which saves time in typing. Also, the values in the array are separated by commas and the key for each value is implied. JavaScript will assign each value to a key position that starts at zero.

If you would like to take advantage of the multiple ways you can write arrays, take a look at these other (equivalent) variations:

Code:
var sampleArray = new Array("car", "bus", "train");

Code:
var sampleArray = Array("car", "bus", "train");

If you’re curious about the length of your array, or more simply put, the number of keys your array has, you can use the JavaScript length property.

Code:
var sampleArray = ["car", "bus", "train"];
console.log(sampleArray.length);

For the example above, the output would be:

3

That’s the number of values in the array.

Array Methods

You can use array methods to manipulate your arrays.

If we use the same example from above, and attach a built in array method to it, the output will be different.

Code:
var sampleArray = ["car", "bus", "train"];
var reverseSampleArray = sampleArray.reverse();
console.log( reverseSampleArray.join() );

In the first line of the example above, I created an array named “sampleArray.” I gave it three values. Then, in the second line, I created another array. This time, I named it “reverseSampleArray” and gave it the value of my first array, but in reverse. The “reverse” method that’s built into JavaScript. All this does is output the reverse of what’s in your initial array.

Lastly, I output the values of the reverseSampleArray as one string. I did this by using the JavaScript “join” method. The join method joins all values of an array into a single value. The output of all this would be:

train,bus,car

Numbers​

If you look back to my post on Data Types in PHP, you’ll see that PHP recognizes multiple types of numbers. One type is the integer and another type is the float, or floating type number. Those two types are differentiated in PHP, but they aren’t in Javascript. In JavaScript, a number is a number, no matter if there is a decimal place in it or not.

When dealing with numbers in JavaScript, there are a few somewhat confusing areas you need to be aware of. I’ll go over them below.

Let’s say you have two variables. Both variable values are numbers. In your code block, you want to add both of these numbers together. Easy enough.

Code:
var firstNumber = 25;
var secondNumber = 35;
console.log(firstNumber + secondNumber);

The output would be:

60

Now, lets change those number values to string values by adding quotes around them.

Code:
var firstNumber = "25";
var secondNumber = "35";
console.log(firstNumber + secondNumber);

In this case, since JavaScript can’t add the two strings as numbers anymore, it adds them as if they were just elements. It concatenates them. It simply puts them together and the output would be:

2535

Just as if it combines two strings, which it does. This is fine for some numbers that should be taken and placed together literally, but not when it comes to addition.

NaN

Now, if you try to use another type of operator in JavaScript – one that can’t add or concatenate, your result would look different.

Code:
var firstNumber = "25";
var secondNumber = "35";
console.log(firstNumber * secondNumber);

In the case above, we are attempting to multiply the two strings. In doing this, we would get the following result:

NaN

That stands for Not-a-Number. If you were truly interested in having the values of the variables above actual numbers, you could turn them into them by using the Number() function in JavaScript. Let’s play around with the example from above again.

Code:
var firstNumber = "25";
var secondNumber = "35";
var makeFirstNumber = Number(firstNumber);
var makeSecondNumber = Number(secondNumber);
console.log(makeFirstNumber * makeSecondNumber);

By using the Number() function that’s built into JavaScript, we can make real numbers from numbers that are treated as strings. In the case above, the output would be:

875

If there really is a string of letters or some other characters that can’t be converted into numbers, you’ll end up with NaN again.

Even after you attempt to turn your string number into a real number, there is a way to test whether or not you’ve really got a number. This is helpful in many cases, such as web form submissions. To test your variable, you can use the isNaN() function.

Code:
if (isNaN(makeFirstNumber) {
    console.log("Sorry. You do not have a number.");
}

In the above example function, I’m using the isNaN() function to test whether or not the makeFirstNumber variable is a number or not. If it isn’t, then we’ll get a response that says, “Sorry. You do not have a number.” If it is a number, nothing will happen. We can also write the function above to include an else statement to get a response if it is a number.

Code:
if (isNaN(makeFirstNumber) {
    console.log("Sorry. You do not have a number.");
} else {
    console.log("Great! You do have a number.");
}

Now, if it really is a number, we’ll receive the output, “Great! You do have a number.”

Math Object

In JavaScript, you can use the Math Object to manipulate numbers. Here are a few examples with outputs below.

Code:
var myNumber = 25.1;
var roundNumber = Math.round(myNumber);

The output would be rounded up and is 26.

Code:
Math.min(3, 200, 50, 70, -100);

This one would return the smallest number, or -100.

Code:
Math.max(3, 200, 50, 70, -100);

This one would return the largest number, or 200.

You can view more like this here.

Strings​

In JavaScript, strings are sequences of text.

Quotes

Strings are enclosed in quotes and those quotes are either single or double. You can’t mix the two. Here’s an example of a string in quotes:

Code:
var myName = "Tom";
var myName = 'Tom';

Strings can’t look like this:

Code:
var myName = "Tom';

Notice the double and single quote surrounding the value.

Escaping Characters

If you have a special case where you run into an issue because you need to enclose quotes inside your string, you can escape those characters like this:

Code:
var myName = "My name is Tom and I've always said, \"I don't care what you think.\"";

By escaping the double quotes above, I indicated that I don’t want the quotes inside my string to be misinterpreted as actually closing the string. If I had used single quotes to surround my string, I could have left the double quotes unescaped and just escaped the single quotes like this:

Code:
var myName = 'My name is Tom and I\'ve always said, "I don\'t care what you think."';

It’s the same exact thing. I just reversed the quotes.

Properties & Methods

Since strings are objects and can be treated as arrays of characters, properties and methods are available to them. To take a look at these, please check out this page. There are quite a few listed. I’ll give you a few examples below:

Code:
var myName = "My name is Tom.";
console.log(myName.length);

The output to the console would be:

15

An example of a method would be something like this:

Code:
var myName = "My name is Tom.";
console.log( myName.toUpperCase() );

The output here would be:

MY NAME IS TOM.

String Comparison

When comparing two strings with the same text in them, the case matters. For example, if you had these two strings:

Code:
var myName1 = "My name is Tom.";
var myName2 = "my name is Tom.";

They would not be considered equal because the “M” and the “J” are of two different cases. If you wanted to make both strings equal, you would need to use either the toLowerCase() method or the toUpperCase() method to equalize them. To learn a bit more about comparing strings, check out this page.

Dates​

When working with dates in JavaScript, you have a few options. You can set the Date() function to years, months, days, hours, minutes, seconds and milliseconds. I’ll give you a few examples below:

Code:
var now = new Date();

The above example will output the current date and time.

If you’d like, you can pass in your own date. That would look like this:

Code:
var newDate = new Date(2000,0,1);

This will output the first day of the first month of the year 2000. Notice how the month is zero based, but the day is not.

JavaScript Date Methods

Date methods are used when you would like to get only a certain section of the date. Here are some examples of that:

Code:
var now = new Date();
now.getMonth();

This would return a digit for the current month.

Code:
var now = new Date();
now.getFullYear();

This would return the digits for the full year, such as 2015.

For more information on the methods used for dates, please take a look at this page.

Similar to the get methods used for the date() function, we also have set methods available to us. If you’d like to see some of them, simply click the link above and scroll down on the page a bit. The set methods are there for you to see.

Here are a few examples for you:

Code:
var now = new Date();
now.setFullYear(2015);

This will set the full year for you.

Code:
var now = new Date();
now.setDate(5);

This will set the day of the month in integers between 1 and 31.

Objects​

In almost every class I’ve ever taken on JavaScript, objects in programming have been described as very similar to objects in the physical world. Both types of objects have properties and characteristics. Now, I know that doesn’t help much because we need to see what an object in programming looks like. Describing it as a car isn’t going to cut it.

In this post, we’ve already gone over objects. Arrays are objects and so are dates. You can apply methods to both of them. Think of objects as variables that can contain many values. Here’s an example of an object in JavaScript:

Code:
var bicycle = {type:"BMX", model:"Mongoose", color:"White"};

In the example above, all I did was create an object that has three properties, or name value pairs. I enclosed them in curly braces, which indicates the object itself. I separated the name value pairs by commas and enclosed the strings in quotes. The example I gave above is written in shorthand. If you’d like to learn more about creating objects written in longhand, take a look at this page.

If we’d like to output a specific piece of data from the above object, we could do that:

Code:
console.log(bicycle.type);

The output would be BMX.

I’m not going to go further into objects right now because I plan on writing posts exclusively covering them. They are quite involved – the way you can create methods for them and associate them with functions. If you’re interested in those future posts, check out the Coding forum up above.
 
EmeraldHike

EmeraldHike

Member
Joined
May 10, 2021
Messages
133
Reaction Score
0
Points
21
  • #4

What is the DOM?​

There’s this thing out there that’s sort of tricky to understand. It’s called the DOM, or Document Object Model. It’s one of those things where if you don’t grasp it early on, your days of JavaScript programming will either be very short, at the very worst, or much more difficult than they need to be, at the very best. Trust me when I say this – It’s in your interest to read up on and understand what the DOM is as early as possible. Not only will you feel like a hero after you figure out what’s going on, you’ll also be paving the way for smooth sailing in the years to come.

So, What’s the DOM?​

I can give you the, sort of, difficult to understand, “official” definition of the DOM here. It most likely won’t get you any closer to coming to grips with what’s happening, but for the sake of inclusion, here goes:

“The Document Object Model is a platform – and language-neutral interface that will allow programs and scripts to dynamically access and update the content, structure and style of documents. The document can be further processed and the results of that processing can be incorporated back into the presented page. This is an overview of DOM-related materials here at W3C and around the web.” (source)

If you really look at and think about the definition above, you can take away a few points. Without more background and explanation though, it’s lacking.

In order to best explain what the DOM is, I think it would be wise to break apart the phrase, Document – Object – Model. Let’s first look at the document.

What is the Document?

I have to say, Simon Allardice really did a great job explaining things in his video on the DOM. Since I haven’t been able to find anything in writing that compares, I’m going to attempt to paraphrase what he said here. At the bottom of this post though, I’ll link to a few references where you can read about the DOM further.

Whenever I discuss the document, I like to think that if I put my arms around my monitor and give it a big hug, I’d be hugging the document. The document is the page we’re looking at in all its variations. If you look at a web page through your browser the normal way anyone would, you’re looking at the document – colors, pictures and all. If you then right click with your mouse on the page and choose, “View Source,” you’d see the HTML code that made up that page. That’s the document too. The way JavaScript views the page is different than you or I would view it, but JavaScript’s view is the document as well. It’s sort of like looking at a document you’re typing in Microsoft Word and clicking on the paragraph button, so you can visibly see exactly where every paragraph ends. Even though you can’t see those paragraph endings in normal view, it doesn’t mean they aren’t there. Everything, including all variations of code, that it takes to make up a web page is considered the document.

While understanding the document is important, I don’t think it’s as critically important of a concept to grasp as the object part of the DOM. After all, it’s the objects that you’re going to be playing with during all that JavaScript coding you’ll be doing.

What is the Object?

Simon Allardice explained objects in the document as “things.” He said that headlines on a webpage are objects, as well are paragraphs, pictures, etc… If you’re looking at the source HTML code of a web page, tags and elements are objects. The text part of the page elements are also objects. I’ll give you some example code below and then go over what would be considered objects in that code.

Code:
<!DOCTYPE html>
<html>
    <head>
        <title>This is my title</head>
    </head>
    <body>
        <h1>My First Heading</h1>
        <p>My first paragraph.</p>
        <ul>
            <li>Text</li>
            <li>Text</li>
            <li>Text</li>
        </ul>
    </body>
</html>

If you look at the above code, each line can be considered an object. The thing is, if you look inside the H1 element, the text withing the element is also considered an object. The same thing goes for the paragraph element. Each list item is considered an object as well as the unordered list itself, so that’s an object within an object.

It’ll take some practice to become comfortable with objects in the document and what you can do with them, but that’s really the heart of JavaScript. Manipulating objects. As you code and code and code, it’ll become second nature.

All we have left now is the model part of the DOM. The idea behind this is fairly straightforward because we’ve probably seen models throughout our entire lives. All a model is, is an easy to understand interpretation of something more complex. Take a schematic or a family tree for instance – those are models. Let’s answer the final question.

What is the Model?

If we think of our HTML code as a tree structure, we can begin to understand what the model of the DOM looks like. We can think of our code more graphically to assist us. Take a look at this image from the W3C.

dom.gif

That image represents the following code of an HTML table:

Code:
<TABLE>
<TBODY>
<TR>
<TD>Shady Grove</TD>
<TD>Aeolian</TD>
</TR>
<TR>
<TD>Over the River, Charlie</TD>       
<TD>Dorian</TD>
</TR>
</TBODY>
</TABLE>

As you can see, the top of the model begins with the TABLE tag and filters down throughout all other elements that follow. The parts of the above code, such as the “TBODY” tag or the “Shady Grove” text are called, “nodes.” Nodes can have parent and children nodes and this is how JavaScript interprets what to manipulate during its processing of code. The model part of the DOM refers to exactly what the nodes are called and how they relate to one another. It’s their interaction and their structure that creates the model.

I tried my best to describe what the DOM is, but I think I’ll always feel my description didn’t go nearly far enough. If I had to describe the DOM to someone the simplest way I could, I’d say that “the DOM can be described as how all the pieces of what creates a web page can be identified, react and relate to one another.” That, my friends, is the best I could do.

As promised, I’m going to list a few sites below that can help you further with this topic. The DOM can get much more technical than the ideas I just expressed, so it’s really a good idea to get as familiar with what’s going on from as many sources as possible.

What is the DOM? by CSS-Tricks

What is the Document Object Model?

Introduction – Web API Interfaces by MDN

JavaScript HTML DOM by W3Schools

JavaScript – W3C DOM – Introduction by QuirksMode
 
EmeraldHike

EmeraldHike

Member
Joined
May 10, 2021
Messages
133
Reaction Score
0
Points
21
  • #5

Accessing, Changing & Creating DOM Elements in JavaScript​

This is where JavaScript really starts to get fun. In this post, I’m going to go over exactly how to use JavaScript methods to access, change and create elements. If you’re a beginner in JavaScript, I suggest you simply read and absorb. After that, head out into the world of the internet and look up everything you can on the topics I cover below. Learning JavaScript is mostly about exposure – the more you can get, the more comfortable you’ll become with what the language is. Let’s get going.

Accessing DOM Elements​

In this section, I’m going to cover a few methods to access elements in the DOM.

getElementById() Method​

By using the getElementById() method, you are able to access an element that has a unique ID in the HTML code of a web page. This is probably the most common method of accessing and manipulating elements in JavaScript.

Below, I’ll give some examples of how this works. Beneath the code, I’ll explain what’s going on.

Code:
document.getElementById(elementID)

This is the standard syntax for this method. As you can see in the above code, you are accessing the document first, then searching for a general element by an ID and then specifying the actual element itself. It’s sort of like a chain – you need to start at the beginning.

In order to understand how this works, I’ll give a short example of some HTML:

Code:
<!DOCTYPE html>
<html>
<head>
    <title>Example Page</title>
</head>
<body>
    <p id="firstParagraph">This is the content of my first paragraph.</p>
</body>
</html>

Now, I’ll write some JavaScript:

Code:
var firstParagraphText = document.getElementById("firstParagraph");

By writing this JavaScript code, I have accessed the p element in my HTML code and set it to the variable, “firstParagraphText.” If I wanted to display just the text within the element (in between the element tags), I would need to use the innerHTML property. I’ll talk more about the innerHTML property in later posts. For now, just remember that the innerHTML property sets or returns the HTML content of an element.

Let’s look at some code.

Code:
<!DOCTYPE html>
<html>
<head>
    <title>Example Page</title>
</head>
<body>
    <p id="firstParagraph">This is the content of my first paragraph.</p>
   
<script>
    var firstParagraphText = document.getElementById("firstParagraph");
    console.log(firstParagraphText);
</script>
 
</body>
</html>

If I run this code in a browser and looked at the console, I’d see the following:

Code:
<p id="firstParagraph">This is the content of my first paragraph.</p>

The reason I’m seeing the entire element is because that’s what I accessed by using the getElementById() method in JavaScript. If I wanted only the text in between the tags, like I mentioned above, I would need to take advantage of the innerHTML property.

Code:
<!DOCTYPE html>
<html>
<head>
    <title>Example Page</title>
</head>
<body>
    <p id="firstParagraph">This is the content of my first paragraph.</p>
   
<script>
    var firstParagraphText = document.getElementById("firstParagraph");
    console.log(firstParagraphText.innerHTML);
</script>
 
</body>
</html>

If you’ll notice in the code above, I added the innerHTML right after the variable, “firstParagraphText” in the second line of the script. Now, the output in the console is just the text:

This is the content of my first paragraph.

Just a quick note – if no elements with the ID I’m looking for exist on the page, I’ll get null as the output. Also, if more than one element with a particular ID exists on the page, the first element will be the output. Further elements will be ignored.

getElementsByTagName() Method​

Let’s say I updated my code to include a second paragraph and an unordered list and I wanted to access elements on my page by tag name, instead of by ID. The syntax I would need to use would look like this:

Code:
document.getElementsByTagName(tagname)

The code I would need to use would look like this:

Code:
<!DOCTYPE html>
<html>
<head>
    <title>Example Page</title>
</head>
<body>
    <p id="firstParagraph">This is the content of my first paragraph.</p>
    <p id="secondParagraph">This is the content of my second paragraph.</p>
   
    <ul>
      <li>First list item</li>
      <li>Second list item</li>
      <li>Third list item</li>
    </ul>
   
    <script>
        var paragraphElements = document.getElementsByTagName("p");
        var listItemElements = document.getElementsByTagName("li");
        console.log(paragraphElements.length);
        console.log(listItemElements.length);
    </script>
 
</body>
</html>

In the above code, you can see my two paragraphs and the list I created. Below those elements, I wrote some code. In the first two lines of code, I accessed two types of elements by tag name and set them to variables. By doing this, I created two arrays in the computer’s memory. Those arrays are going to be filled with as many of those types of elements that are on the page. It doesn’t matter how many there are – if they are the same type of element, they’ll be captured.

In the next two lines of code, I output the length of each array in the console. In this case, the output is:

2
3

Let’s have a little fun. Since we can access our arrays (the above variables) by index, we can output the inner HTML of whichever element we want. Take a look at this code:

Code:
<!DOCTYPE html>
<html>
<head>
    <title>Example Page</title>
</head>
<body>
    <p id="firstParagraph">This is the content of my first paragraph.</p>
    <p id="secondParagraph">This is the content of my second paragraph.</p>
   
    <ul>
      <li>First list item</li>
      <li>Second list item</li>
      <li>Third list item</li>
    </ul>
   
    <script>
        var paragraphElements = document.getElementsByTagName("p");
        var listItemElements = document.getElementsByTagName("li");
        console.log(paragraphElements[0].innerHTML);
        console.log(listItemElements[1].innerHTML);
    </script>
 
</body>
</html>

Notice how I changed the console.log statements. Now, I’m accessing the first element (the 0 index) of the paragraphElements array and the second element (the 1 index) of the listItemElements array. In these statements, I’m only looking to output the text that’s in the elements, in between the tags. For this, I again use the innerHTML property. The output looks like this:

This is the content of my first paragraph.
Second list item


How cool is that?

Retrieving Only Certain Elements​

We have a little problem. In the last code example I gave, the getElementsByTagName() method accessed all elements of a tag name. What if we only wanted to access certain elements of a tag name? What if we had two unordered lists and we only wanted to access one? Take a look at the following code:

Code:
<!DOCTYPE html>
<html>
<head>
    <title>Example Page</title>
</head>
<body>
   
    <ul id="firstList">
      <li>First list item</li>
      <li>Second list item</li>
      <li>Third list item</li>
    </ul>
   
    <ul id="secondList">
      <li>Fourth list item</li>
      <li>Fifth list item</li>
      <li>Sixth list item</li>
    </ul>
   
    <script>
        var listItemElements = document.getElementsByTagName("li");
        console.log(listItemElements.length);
    </script>
 
</body>
</html>

If I were to run this page and look at the output in the console, I’d see “6.” That’s the length of the array I created. If we wanted to access the first list only, we’d have to modify the script code to look like this:


Code:
<!DOCTYPE html>
<html>
<head>
    <title>Example Page</title>
</head>
<body>
   
    <ul id="firstList">
      <li>First list item</li>
      <li>Second list item</li>
      <li>Third list item</li>
    </ul>
   
    <ul id="secondList">
      <li>Fourth list item</li>
      <li>Fifth list item</li>
      <li>Sixth list item</li>
    </ul>
   
    <script>
        var firstListElements = document.getElementById("firstList");
        var listItemElements = firstListElements.getElementsByTagName("li");
        console.log(listItemElements.length);
    </script>
 
</body>
</html>

Since I want to limit my access to just one unordered list, I can’t begin my search at the document level. I need to create a new “search zone” of limited scope. To do this, I accessed the list with the ID of “firstList” and set that to a variable named, “firstListElements.” After that, I used the getElementsByTagName() method again, but this time, I didn’t begin with “document.” I began with my newly created zone of “firstListElements.” I continued as I normally would and my output was now:

3

That’s how you can refine a blunt instrument and narrow your HTML to get your desired output.

Changing DOM Elements​

The first step in changing an element is to get the element. In the last section, we accessed the elements in question, so that’s done. In this section, I’m going to write some code that will show you how to change an element. I’m going to start off really easy and simply continue on using my very last example. Let’s look at some code:

Code:
<!DOCTYPE html>
<html>
<head>
    <title>Example Page</title>
</head>
<body>
   
    <ul id="firstList">
      <li>First list item</li>
      <li>Second list item</li>
      <li>Third list item</li>
    </ul>
   
    <ul id="secondList">
      <li>Fourth list item</li>
      <li>Fifth list item</li>
      <li>Sixth list item</li>
    </ul>
   
    <script>
        var firstListElements = document.getElementById("firstList");
        var listItemElements = firstListElements.getElementsByTagName("li");
        listItemElements[2].innerHTML = "<strong>This list item has been CHANGED!!!</strong>";
    </script>
 
</body>
</html>

Can you guess what the output of this page would be? Here, take a look:

First list item
Second list item
This list item has been CHANGED!!!

Fourth list item
Fifth list item
Sixth list item

Okay, so here’s what happened. Just like last time, I accessed the firstList ID in the first list and set that to a variable named firstListElements. Then, I accessed the li elements only in the first list and stored them in a variable called listItemElements. After that, I changed the third list item (index number 2) inner HTML, or text, to output “This list item has been CHANGED!!!” in bold. As you can see, if you’ve done all the work to get the element or ID, it’s not too difficult to change something about it. Let’s look at some more examples.

Say we wanted to change the alignment of an specific area of a page. We could do that. Take a look at this code:

Code:
<!DOCTYPE html>
<html>
<head>
    <title>Example Page</title>
</head>
<body>
   
    <div id="mainContent">
        <h1>This is the Main Title</h1>
        <p>This is the main paragraph.</p>
    </div>
   
    <script>
        var mainContent = document.getElementById("mainContent");
        mainContent.setAttribute("align", "right");
    </script>
 
</body>
</html>

In the above example, I used the setAttribute() Method. That method looks like this:

Code:
element.setAttribute(name, value);

It’s defined as, “Adds a new attribute or changes the value of an existing attribute on the specified element.”

Now knowing this, we can go through the above example. In this code, I added an h1 element and a p element. In both spaces, I typed in some filler text. In the script area, I used the getElementById() method to access the id, “mainContent” in the div element. I stored that data in a variable called “mainContent.” After that, I set the align attribute of the variable I created (the mainContent ID in the dev element) to right. Now, both the h1 and the p elements are aligned to the right.

Here’s another one for you. Say we had a style set in the head area of our page and we wanted to apply the style to a particular element in our page. In the code below, I created a style, but by default, it isn’t connected to anything. If we use a little JavaScript, we can change that. Take a look:

Code:
<!DOCTYPE html>
<html>
<head>
    <title>Example Page</title>
    <style>
        .red-class {
        color: red;
        }
    </style>
</head>
<body>
   
    <div id="mainContent">
        <h1>This is the Main Title</h1>
        <p>This is the main paragraph.</p>
    </div>
   
    <script>
        document.getElementsByTagName("h1")[0].setAttribute("class", "red-class");
    </script>
 
</body>
</html>

What I did above was to get the h1 element (the first one in the array with the index of 0) and then I created a class for it named “red-class.” Now, when the page is loaded, any text within the h1 element will be red because the h1 element is now connected to the style I created in the head section. What wasn’t before, now is.

If I wanted to go one step further and actually change the text that’s between the h1 tags, I can do that:

Code:
<!DOCTYPE html>
<html>
<head>
    <title>Example Page</title>
    <style>
        .red-class {
        color: red;
        }
    </style>
</head>
<body>
   
    <div id="mainContent">
        <h1>This is the Main Title</h1>
        <p>This is the main paragraph.</p>
    </div>
   
    <script>
        document.getElementsByTagName("h1")[0].setAttribute("class", "red-class");
        document.getElementsByTagName("h1")[0].innerHTML = "This is the NEW Main Title!!!";
    </script>
 
</body>
</html>

By adding the line:

Code:
document.getElementsByTagName("h1")[0].innerHTML = "This is the NEW Main Title!!!";

I changed the inner HTML of the h1 element. Now, this new line of text appears in the place of the original text.

Creating DOM Elements​

This area of JavaScript is very exciting. It’s actually sort of empowering. When you’re finished reading what I write below, I’m sure you’ll say what I said – “Wow, that’s really cool!”

I’m going to attempt to explain the whole idea of creating elements with JavaScript as clearly as I can. If I miss anything, please let me know in the comment section below. All right – let’s go.

There are a few ways to create elements with JavaScript and “insert” them into a web page. I’ll go over each method that I currently know of below.

There are always two steps we need to take when we want to dynamically insert something into a page:

1. Create the element.
2. Add the element to the document.

Just keep those two things in mind and it’ll help a lot.

Let’s start off with a code example:

Code:
<!DOCTYPE html>
<html>
<head>
    <title>My Example Page</title>
</head>
<body>
   
    <div id="mainContent">
        <h1>This is the Main Title</h1>
        <p>This is the main paragraph.</p>
    </div>
   
    <ul id="listContent">
      <li>First list item</li>
      <li>Second list item</li>
      <li>Third list item</li>
    </ul>
   
    <script>
        var myNewElement = document.createElement("li");
        myNewElement.innerHTML = "Fourth list item";
        document.getElementById("listContent").appendChild(myNewElement);
    </script>
 
</body>
</html>

This one is pretty simple. The goal with the JavaScript code above is to add a fourth list item to the current list of three items. My unordered list has an ID of listContent and each list item has no ID.

If we look at the JavaScript code above, we can see that I wrote three lines of code.

In the first line, I used the createElement() method to create a new li element and stored that element in a variable called myNewElement.

In the second line, I used the innerHTML property to add text within the li element. In this case, the text says, “Fourth list item.”

Finally, in the last line, I used the getElementById() method to get the unordered list I’d like to add the new list item to. After that, I used the appendChild() method to add my new list item to the bottom of the current list.

There you have it – a fourth item in the list. Once you get the hang of it, it’s really not too painful.

Now, there is another way of adding content to the list item, besides using the innerHTML property. We could create an actual text node and add that to our element. Here, look at some more code:

Code:
<!DOCTYPE html>
<html>
<head>
    <title>My Example Page</title>
</head>
<body>
   
    <div id="mainContent">
        <h1>This is the Main Title</h1>
        <p>This is the main paragraph.</p>
    </div>
   
    <ul id="listContent">
      <li>First list item</li>
      <li>Second list item</li>
      <li>Third list item</li>
    </ul>
   
    <script>
        // create new element
        var myNewElement = document.createElement("li");
       
        // create text node
        var listText = document.createTextNode("Fourth list item");
       
        // add text node to new element
        myNewElement.appendChild(listText);
       
        // attach new element to the document
        document.getElementById("listContent").appendChild(myNewElement);
    </script>
 
</body>
</html>

This one should be a bit easier to follow because I added some comments. I think I’m going to do this from now on. Not only does it help you, it helps me as well.

We already know what happened on the first line. We created the new element. On the second line, instead of using the innerHTML property to add the text to the element, we took advantage of the createTextNode() method to create our filler text. On the third line, we put our element and text node together and finally, just like last time, we used the getElementById() method to get the element we want to add our list item to and appended our new element to it.

I actually like this way better because it’s easier on the head. It keeps the steps broken up more.

Here’s a question – What if we want to add our new list item someplace other than at the end of our list? What if we want to add it to the first spot in the list and push the other list items down a spot? Well, we can do that. Take a look at this updated code:

Code:
<!DOCTYPE html>
<html>
<head>
    <title>My Example Page</title>
</head>
<body>
   
    <div id="mainContent">
        <h1>This is the Main Title</h1>
        <p>This is the main paragraph.</p>
    </div>
   
    <ul id="listContent">
      <li>First list item</li>
      <li>Second list item</li>
      <li>Third list item</li>
    </ul>
   
    <script>
        // create new element
        var myNewElement = document.createElement("li");
       
        // create text node
        var listText = document.createTextNode("Fourth list item");
       
        // add text node to new element
        myNewElement.appendChild(listText);
       
        // get the list
        var newList = document.getElementById("listContent");
       
        // insert new list item
        newList.insertBefore(myNewElement, newList.childNodes[0]);
    </script>
 
</body>
</html>

In the above code, I removed the last line from the previous example and replaced it with two new lines. In the fourth line now, I used the getElementById() method to get the list we want to add the new list item to and stored that in a variable named newList. In the last line, I used the insertBefore() method to define exactly where I wanted to place the new list item. I also used the childNodes property to return the child nodes of the unordered list with the ID of listContent. I also specified which position I’d like to insert the new list item before. In this case, I chose the first list item, or the one with the index of 0.

Well, that’s it for this post. If you’re interested in more JavaScript tutorials, please keep your eye on the Coding forum. I’m constantly adding more fun filled posts.
 
EmeraldHike

EmeraldHike

Member
Joined
May 10, 2021
Messages
133
Reaction Score
0
Points
21
  • #6

JavaScript Events & Event Listeners​

In this post, I’m going to talk about events in JavaScript. Events are those things that happen on, in and around a web page. They are all over and occur even when you think they aren’t. In short, I’ll be talking about what JavaScript can do when someone clicks something, when a page is loaded, when a mouse is moved, when someone fills in a field, when a key on a keyboard is pressed…you get the idea. And since events happen all the time, JavaScript can be utilized quite powerfully, in ways that can truly make your pages come alive.

onclick Event​

The onclick property returns the click event handler code on the current element.

Let’s start writing some code. In this first example, I’m going to give you the most basic of basic scenarios you might find. It doesn’t get any easier than this:

Code:
<script>
document.onclick = function() {
    alert("You clicked anywhere!");   
}
</script>

In this example, I’m using the script tags. This is so I don’t have to set up a real document and link my JavaScript file to it. If this were an actual website, I would do things correctly, but since we’re here to learn, just pretend those script tags aren’t there. If you’d like to try this script out for yourself though, please feel free to copy/paste the above and use it.

Anyway, what we’ve got in the above code is the use of an onclick event. The onclick event occurs when your specified element is clicked by a user. In the case above, I chose to have the entire document as the click target, so if you were to click anywhere on the page, an alert box would pop up with text that says, “You clicked anywhere!” Also, you can see that I’ve got the target (document) tied to the event (onclick) tied to a function (function()). When the event occurs on the target, the function executes. In this case, the function is an alert box.

Let’s try another example and this time, let’s build the page out a bit.

Code:
<!DOCTYPE html>
<html>
<body>
    
<p id="myText">This is my text. Click it if you dare.</p>
    
<script>   
var clickedText = document.getElementById("myText");
clickedText.onclick = function() {
    alert("You clicked the text.");   
}   
</script>
 
</body>
</html>

As you can see, I added some HTML elements, just to make things seem as lifelike as possible.

In this example, I included a paragraph that has an ID associated with it. The ID is called, myText. This is going to help me refine my click target, as opposed to having the entire page a clickable element.

After the paragraph and inside the script tags, I used the getElementById() method to get the ID called myText. After that, I associated myText with a variable that I named clickedText. Now that I have a simple variable, it’s easy to create an event response.

As you can see, after the newly defined variable statement, I created a function that would execute during an onclick event and associated that with my clickedText variable. Now, if someone clicks on the target text, they receive an alert box that says, “You clicked the text.”

Let’s do one more example and this time, let’s throw in some areas we learned about in one of my previous posts. This should be a fun one.

Code:
<!DOCTYPE html>
<html>
<body>
 
<p>Want to try something? Click the button (if you dare).</p>
 
<button onclick="myFunction()">Click Me</button>
 
<p id="myText"></p>
 
<script>
function myFunction() {
    document.getElementById("myText").innerHTML = "You daring fool!";
}
</script>
 
</body>
</html>

Okay, let’s see if I can go through this one clearly.

First, I created a paragraph with an instruction in it. I dared the page visitor to click the button. Inside the button they are supposed to click on, I added the onclick event to coincide with a function that I’ve written towards the bottom of the page.

After the button, I created an empty paragraph element that uses the ID called myText. This paragraph will be populated with the text that’s created when the function directly below it is called by the button click. Still with me?

Let’s talk about the function. Again, we have an anonymous function that holds a statement. This time, we took advantage of what we learned in my previous post and used the getElementById() method to get the ID myText from the empty paragraph above. Once we get that ID, we have the ability to use the innerHTML property to fill the paragraph with some text. In this case, the text is “You daring fool!”

So, to make a short story even shorter, a page visitor is instructed to click a button. Once they click it, a chain reaction is set. The button enacts the myFunction() function, which gets the the myText ID, which gives the ability to populate the above paragraph with text. Cool? If you’d like, you can copy/paste the code to see it work.

onload Event​

An event handler for the load event of a window.

Let’s talk about the “window” for a moment. Here, I grabbed this from the MDN site:

“The window object represents a window containing a DOM document; the document property points to the DOM document loaded in that window.”

So, the window encapsulates the document.

There’s an issue when attaching your JavaScript file to your web page in the wrong spot in your code. If you, for example, call your JavaScript file up in your head element and that file is supposed to run something that hasn’t yet been loaded on your HTML page, nothing will happen. If you load your JavaScript file down at the bottom of your page, right before the closing body tag, then your code will run properly. Due to this issue, some developers choose to use the onload event.

But that’s not what I wanted to talk about today. If you’re interested in the scenario that I just described, you can do some research on it for the best way to handle it.

Let’s go over a quick example of what some JavaScript onload code might look like:

Code:
<!DOCTYPE html>
<html>
<body onload="sayHello()">
 
<script>
function sayHello() {
    alert("Hello There!");
}
</script>
 
</body>
</html>

The code above is very simple. As you can see, I’ve called the sayHello() function from the opening body tag. So when the page loads, the function will run. In this case, the function opens an alert box that says, “Hello There!”

Here’s another code example:

Code:
<!DOCTYPE html>
<html>
<body onload="sayHello()">
    
<p id="hello"></p>
 
<script>
function sayHello() {
    document.getElementById("hello").innerHTML = "Welcome to my web page.";
}
</script>
 
</body>
</html>

In the above code, I gave pretty much the same example as one of the previous examples in this post, but instead of using the onclick event, I used the onload event. So no user interaction would have to take place beyond visiting the web page in question. In this case, when the user visits this web page and it loads, the following text would be inserted into the paragraph element:

Welcome to my web page.

onfocus & onblur Events​

The onfocus and onblur events often work together and often can be found hanging around web forms. In the most simple sense, the onfocus event triggers an event when an element is focused upon, such as a form field being clicked on. The onblur event is the opposite – an event is triggered when an element’s focus is removed, such as a form field being clicked away from. Let’s see these two in action.

Code:
<!DOCTYPE html>
<html>
<body>
 
Type something in the box: <input type="text" id="inputText" onfocus="clickIn()" onblur="clickOut()">
 
<script>
function clickIn() {
    document.getElementById("inputText").style.background = "blue";
}
 
function clickOut() {
    document.getElementById("inputText").style.background = "orange";
}
</script>
 
</body>
</html>

For this first example, I created a form field that asks the user to type something. When the field is clicked in, the background of the field turns blue. When the field is clicked away from, it turns orange.

If you look at the code above, you’ll see that I utilized the onfocus and onblur events right inside the input element. This is one way to do it, but you can also do it another way, which I’ll show you next. Anyway, within the input element, I associated both events with their respective functions called clickIn() and clickOut().

Inside the script element, I wrote two functions. The first one gets the ID from the input element and changes the style (color) of it when it’s clicked on. The second function does the same thing, but changes the color when the element is clicked away from.

Let’s take a look at another code example:

Code:
<!DOCTYPE html>
<html>
<body>
 
Type something in the box: <input type="text" id="inputText" value="Write something here.">
 
<script>   
var inputField = document.getElementById("inputText");
    
inputField.onfocus = function() {
    if ( inputField.value == "Write something here." ) {
        inputField.value = "";   
    }
}
 
inputField.onblur = function() {
    if ( inputField.value == "" ) {
        inputField.value = "Write something here.";   
    }
} 
</script>
 
</body>
</html>

In the above code, I (again) created an input field. This time, I didn’t include any events inside this element. I simply named it with an ID of inputText. I also gave the field an initial value of “Write something here.”

If you look further down into the script element, you’ll see that I used the getElementById() method to get the inputText ID and then I stored it in a variable called, inputField. Then, I wrote two functions using that variable. The first function uses the onfocus event and the second uses the onblur event. Both functions include an if statement that asks whether or not something exists.

In the first function, the if statement asks if the value “Write something here.” exists when the input field is clicked on. If it does, change the value to nothing. In the second function, the if statement asks if the field is empty when the field is clicked away from. If it is, insert the field with the value, “Write something here.” Pretty cool.

Timing Events​

In JavaScript, when you’d like to execute some code at specified time-intervals, you set it. When you want to stop the time-intevals, you clear it. When it comes to setting, there are generally two timing events you want to concern yourself with. They are setInterval() and setTimeout(). When it comes to clearing, again, there are generally two timing events you want to concern yourself with. They are clearInterval() and clearTimeout().

Take a look at these quick definitions:

setInterval() – The setInterval() function initiates a function, again and again, specifically at the times you set.

setTimeout() – The setTimeout() function initiates a function after waiting the amount of time you set.

clearInterval() – The clearInterval() function stops the function that was initially executed by the setInterval() function.

clearTimeout() – The clearTimeout() function stops the function from executing that was initiated by the setTimeout() function.

In order to make the above ideas more clear, I’m going to give some code examples. As usual, I’ll go over them below.

The first example I’m going to give is really simple. It’s just to show you how the setTimeout() function can possibly work. Take a look:

Code:
<!DOCTYPE html>
<html>
<body>
 
<p id="pageText"></p>
 
<script>
function putText() {
    document.getElementById("pageText").innerHTML = "This text took 5 seconds to appear.";
}
    
setTimeout(putText,5000);
</script>
 
</body>
</html>

Like previous examples, I placed an empty paragraph element in the page and used an ID, but this time called it pageText. After that, I wrote a function and used the getElementById() method to get the paragraph ID. After that, I used the innerHTML property to set the text inside the paragraph to “This text took 5 seconds to appear.” The only thing I had left to do was to somehow make the text appear. In this case, I chose to use the setTimeout() function to hold back the appearance of the text by five seconds.

In this next example, we’re going to clear the timeout.

Code:
<!DOCTYPE html>
<html>
<body>
 
<p id="pageText"></p>
 
<script>
function putText() {
    document.getElementById("pageText").innerHTML = "This text took 5 seconds to appear.";
}
    
timer = setTimeout(putText,5000);
</script>
    
<button onclick="clearTimeout(timer)">Stop the Text From Appearing</button>
 
</body>
</html>

This is the same code as above, but with a few modifications. First, in order for the clearTimeout() function to work, I needed to set the setTimeout() function to a variable. I did that and called the variable “timer.” Next, I used a button for the clearTimeout() function. When the button is clicked, the clears the timeout variable and halts the text from appearing on the page. The only thing is, the button needs to be clicked some time within the five seconds before the text appears.

Now, let’s take a look at the setInterval() function. Check out the code below:

Code:
<!DOCTYPE html>
<html>
<body>
    
<script>   
function alertBox() {
    alert("Hello There");
}
    
setInterval(alertBox,3000);   
</script>
 
</body>
</html>

In the above code, I wrote a function called alertBox that pops up an alert box every three seconds. The first alert box takes three seconds to appear and once you close the box, the box waits another three seconds before it appears again. This will go on forever, unless you stop it. To do that, take a look below:

Code:
<!DOCTYPE html>
<html>
<body>
    
<button onclick="clearInterval(popUp)">Stop The Damn Box</button>
    
<script>   
function alertBox() {
    alert("Hello There");
}
    
var popUp = setInterval(alertBox,3000);
</script>
 
</body>
</html>

Looks familiar, doesn’t it? Just like last time with the setTimeout() function, in order to stop the setInterval() function from continuing on forever, we had to set it to a variable. This time, I named the variable “popUp.” By doing this, we had a variable to clear. In order to take advantage of that, I created a button outside the script with the clearInterval() function inside of it. When a user clicks the button, the alert box stops appearing. It’s that simple.
 
Top