Basic JavaScript Tutorial

Ghost

Seasoned Veteran
Blogger
Jun 25, 2009
3,198
185
213
Earth
wubur.com
FP$
2,483
Learning JavaScript is not as difficult as you may think. The language is used for a variety of things on websites including changing what your visitors see, sending data to another part of your website, temporarily storing user information, validating contact form data, and many other useful utilities that make the user experience so much better.

In this extremely basic tutorial, you will learn some beginner JavaScript regarding variables, and showing those variables on your website (inside HTML). If you want to learn the same thing in PHP and some more you can do so, with my Basic PHP Tutorial.

If you see anything in italics, it is part of our tutorial.html code.

To start, we will need an HTML file. For this tutorial we will be doing all of our coding in a file called 'tutorial.html' and we will not be linking to a separate JavaScript file (ex: tutorial.html could link to a separate file called tutorial.js).

Create your file called tutorial.html on your desktop. You can open it up in any web browser you want, and it will all work!

tutorial.html
<script>
// we start a JavaScript segment inside a HTML file by using <script>

// you can use double slash to start a one-line comment in JavaScript

// we end a JavaScript segment inside a HTML file by using </script>
</script>

Our JavaScript starts with the <script> tag whenever we are including the code inside of an HTML file. If we were linking to another file (like something.js) then we would not need to use the <script> tags because the browser already knows it's JavaScript from the .js extension. Remember that for this tutorial, we are doing everything inside of tutorial.html

Go ahead and open up your file in your browser. You will notice that nothing has happened. This is because we have done anything inside of our script tags. Let's begin by declaring a JavaScript variable. We do so with the term 'var', followed by our variable name.

tutorial.html
<script>
// we start a JavaScript segment inside a HTML file by using <script>

// let's declare some variables with 'var':


var myname = "William";

// a line of JavaScript should end with a semicolon ( ; ), but will still work without one as long as the next statement is on a new line


var username = 'Ghost';

// you will notice that for myname I used double quotes ( " ), but for username I used single quotes ( ' ). Both will work for JavaScript strings, but I prefer to stick to one type for the whole block of code.


var age = 25;

// There are no quotes around my age because this is an integer. Numbers in JavaScript do not require quotes around them unless you specifically want to make sure the variable's value is a 'string'

// we end a JavaScript segment inside a HTML file by using </script>
</script>




If you read through the comments, you will now know two different ways to declare a string variable in JavaScript, as well as how to declare an integer. However, we did not declare our variables efficiently. There is a much better way to declare multiple variables at once and we will do so now:

tutorial.html
<script>
// we start a JavaScript segment inside a HTML file by using <script>

// let's declare some variables with 'var':
var myname = "William",
username = "Ghost",
age = 25;


/*
As you can see, instead of a semi-colon at the end of each variable's value and 'var' at the beginning, I only used var once and only a semi-colon at the end.

This is because you can declare multiple variables by using var at the start, and then putting a comma after each variable's value.

This is a more efficient and cleaner way to declare multiple variables.
Use a semi-colon ( ; ) at the end of the LAST declared variable's value to let JavaScript know you are done.
*/

// we end a JavaScript segment inside a HTML file by using </script>
</script>


Now you know how to declare multiple variables, and you may have noticed I used /* and */ inside the code. When you use double-slash ( // ), you are telling JavaScript that you want to have a 'one-line' comment, or text that isn't code. Because it's one line, you cannot press enter to separate your sentences. With /* and */, you can have a multi-line comment. JavaScript will ignore all of the text inside of those comment start/end tags, even if you have multiple lines separated by blank lines! It's a great way to remind yourself of what you are doing, without having JavaScript misinterpret your comments as code. You can also use it to leave old code in your script if you want it back later, or test how a script works with a certain piece of code not executing. This is useful for bug testing as you don't have to delete your code, you can just comment it out!

Now, let's learn how to actually look at our variables in our browser. There are two ways, but let's start with the easiest way for development. So far none of our JavaScript is doing anything to our HTML page in our browser, and it should still appear blank for you!

tutorial.html
<script>
// we start a JavaScript segment inside a HTML file by using <script>
// double slash starts a single-line comment

/*
You can use slash-asterisk to start a multi-line comment
You can use asterisk-slash to end a multi-line comment
*/



/* let's declare some variables with 'var'...
The var doesn't even have to be on the same line as the first variable ! */
var
myname = "William",
username = "Ghost",
age = 25;


// let's use console.log() to show our variable in our browser's console
console.log(myname); // let's show one variable
console.log(username, age); // let's show two at once...

// we end a JavaScript segment inside a HTML file by using </script>
</script>

Once you have set up your console.log() code with your variables inside, you should open tutorial.html in your browser. You then need to find the 'console log'. On some browser pressing 'ctrl+shift+i' will open up the developer tools / console log. You can also find them by going to your options menu -> developer tools (or similar). Your console will most likely be a tab a top on this new panel that will appear on the side (but still inside) of your browser window.

Once you have opened up the console log AFTER you have opened/loaded tutorial.html, you will see the following (or whatever your variables are set to equal):
William
Ghost 25

As you can see, my name is on one line, and my username and age are on another line. This is because of the two different ways I used console.log() to see my variables! Now let's actually make the text appear on the page.

tutorial.html
<html>
Name: <span id="myname"></span> <br />
Username: <span id="username"></span> <br />
Age: <span id="age"></span>

</html>


<script>
var
myname = "William",
username = "Ghost",
age = 25;


/*
We can use a function called 'getElementById()', which is part of our HTML document context...
This allows us to target a specific piece of HTML to either evaluate what's there, or even add to it.
Let's add to it!
*/


var nameValue = document.getElementById("myname").innerText,
usernameValue = document.getElementById("username").innerText,
ageValue = document.getElementById("age").innerText;

console.log(nameValue, usernameValue, ageValue);

</script>

If you did this all correctly, you will notice not much has happened. Our HTML is only showing:
Name:
Username:
Age:


We also removed our original console.log(), so our console.log is not showing our set variables from above. We also added a console.log() below to show us the current 'innerText' values of our spans, which we targeted with 'document.getElementById()'

However, we have nothing inside of those span values, so our console log is only showing a blank line! Let's make those spans show some content in them!

tutorial.html
<html>
Name: <span id="myname"></span> <br />
Username: <span id="username"></span> <br />
Age: <span id="age"></span>
</html>

<script>
var
myname = "William",
username = "Ghost",
age = 25;

/*
We can set the values of our span elements by using very similar code as in the previous step.
Instead of using a variable to store the current value, we update the current value by making the document element (identified by ID) to our JavaScript variables above!
*/
document.getElementById("myname").innerText = myname;
document.getElementById("username").innerText = username;
document.getElementById("age").innerText = age;

// now we should get some data because we put our information into those span elements!
var nameValue = document.getElementById("myname").innerText,
usernameValue = document.getElementById("username").innerText,
ageValue = document.getElementById("age").innerText;

console.log(nameValue, usernameValue, ageValue);

</script>


Now we can correctly see our information on the HTML page!
Name: William
Username: Ghost
Age: 25


And because our span elements now have values, our console now shows:
William Ghost 25

So, at this point you may be wondering how this is all useful. Well, in this final part of the beginner JavaScript tutorial I will show you how to take user input, and show it on the page!

For this part we will use a basic HTML text input for each input. We will also add a button that can do things when it's clicked. Please read the comment carefully...

tutorial.html
<html>
Name:<br />
<input id="myname" type="text" />

<br /><br />

Username: <br />
<input id="username" type="text" />

<br /><br />

Age:<br />
<input id="age" type="text" />

<br />
<br />

<button id="submit_button">Submit</button>

</html>

<script>
/*
As you can see, we have our name, username, and age input boxes for the user to type information in. We also have a submit button!

First we need to add an "onclick" event to our button! This basically means "when the user clicks this button".... do something.

We select our button element like we did before, but instead of using innerText, we use onclick...

And just like we were able to set the innerText to a value, we can set the onclick to equal something.... a FUNCTION! A function allows more JavaScript code to be run, and is used to do more than a basic variable. Instead of just equaling a value, we're equaling a series of events or commands!

.onclick = function(){
inside of here, we can make JavaScript do things!
}

Let's do it!
*/

document.getElementById("submit_button").onclick = function(){
console.log('test');
}

</script>

Open up your tutorial.html in your browser & click that button. In your console you will see 'test' ! Woo, you created your first button event with core JavaScript! You're doing great :) Now we need to actually make this useful. Let's learn how to actually grab those values from those input boxes! Instead of onclick or innerText, we're going to use the '.value' property!

tutorial.html
<html>
Name:<br />
<input id="myname" type="text" />

<br /><br />

Username: <br />
<input id="username" type="text" />

<br /><br />

Age:<br />
<input id="age" type="text" />

<br />
<br />

<button id="submit_button">Submit</button>

</html>

<script>

document.getElementById("submit_button").onclick = function(){
var
myname = document.getElementById("myname").value,
username = document.getElementById("username").value,
age = document.getElementById("age").value;

/*
As you can see, you can write your JavaScript code inside of your function so it's only executed when the button is clicked! Comments are fine inside functions too!

Let's console.log whatever we get from our inputs!
*/

console.log(myname, username, age);

} // end of function

</script>


Go ahead and type some things into your input boxes! Whenever you press that button your user-supplied values will show up in console! Woo, we're almost there. Now let's actually get those values to show up on the page.

We first will create a span element with the ID 'response'. We will then do something called 'string concatenation'. This basically allows us to take JavaScript variables and include them in a sentence or block of text.

It works like this...
"My variable equals... " + variableHere;
The plus sign allows me to take a string wrapped in double or single quotes and add to it.
I can even do it more than once like this...
var variableHere = 'hello';
"My variable equals... "
+ variableHere + " ... and I love string concatenation!";
This would be the same as:
"My variable equals... hello ... and I love string concatenation!"

So, let's use some string concatenation in JavaScript to show a message once our user inputs their information and clicks submit!

tutorial.html
<html>
Name:<br />
<input id="myname" type="text" />

<br /><br />

Username: <br />
<input id="username" type="text" />

<br /><br />

Age:<br />
<input id="age" type="text" />

<br />
<br />

<button id="submit_button">Submit</button>

<hr>
<span id="response"></span>

</html>

<script>

document.getElementById("submit_button").onclick = function(){
var
myname = document.getElementById("myname").value,
username = document.getElementById("username").value,
age = document.getElementById("age").value;

/*
As you can see, you can write your JavaScript code inside of your function so it's only executed when the button is clicked! Comments are fine inside functions too!

Let's console.log whatever we get from our inputs!
*/

console.log(myname, username, age);

document.getElementById("response").innerText = "Hello " + myname + ", or should I call you " + username + "? Anyways, I see you are " + age + " years old.";

} // end of function

</script>


Open up tutorial.html, input some values and press submit!
On my page I see:
Hello William, or should I call you Ghost? Anyways, I see you are 25 years old.

Congratulations! You have successfully learned how to...
  • Include JavaScript inside an HTML file: <script></script> tags
  • Declare a variable: var variableName = 'something';
  • Use console: console.log()
  • Store an HTML element's text or value : variable = document.getElementById('html_id_here').innerText (or .value)
  • Change an HTML elemeent's text / value: document.getElementById('html_id_here').innerText (or .value) = variableName;
  • Add an event to a button click: document.getElementById("id").onclick = function(){ // do stuff }
  • Concatenate strings: "text can go here" + variableName + anotherVariableName + "more text";
I hope this tutorial helped you understand JavaScript a bit better, and hopefully you can start creating some cool things. With all of this knowledge you can start creating your own basic text RPG, cool forms, or even a calculator. Of course, there's more to learn... You should probably know about if statements, sanitizing user input (making the data safe from malicious attacks), or validating input types (example: making sure something is in fact a number), but this should help you get started.

If you know someone that is wanting to learn JavaScript, please send them this link!
 

Azareal

Paragon
Tip: Use code BBCode instead of italics.

JavaScript:
function blah() {
}
MDN usually has good resources for this.

Also, the DOM and scopes are more advanced than one might think to an absolute beginner.
Supposedly, the reason Excel is so popular is because it has absolutely no scopes.
 

Lämmchen

Addicted
Community Team
Feb 10, 2019
997
268
73
FP$
423
When I was doing web pages ages ago I would look at how other people did their javascript so I could copy the technique. Your tutorials are really great and maybe someday I'll get the confidence to get back into my portrait business and build my webpage that is more modern.
 

Ghost

Seasoned Veteran
Blogger
Jun 25, 2009
3,198
185
213
Earth
wubur.com
FP$
2,483
Wow! Nice share, very useful :)
Thanks Malcolm I appreciate it!

Another great tutorial, thank you @Ghost! :bluesquarerolleyes:
:( cheers Dantrex!
Any other types of tutorials you’d like to see?

Tip: Use code BBCode instead of italics.

JavaScript:
function blah() {
}
MDN usually has good resources for this.

Also, the DOM and scopes are more advanced than one might think to an absolute beginner.
Supposedly, the reason Excel is so popular is because it has absolutely no scopes.
I couldn’t find the CODE tags hiding in the drop down options! :(
I’ll add the tags or do it next time

When I was doing web pages ages ago I would look at how other people did their javascript so I could copy the technique. Your tutorials are really great and maybe someday I'll get the confidence to get back into my portrait business and build my webpage that is more modern.
That’s exactly how I learned everything. I was introduced by changing other people’s code and then I picked up on things. Then I made the conscious effort to learn online until I was able to make my own projects
 
  • Like
Reactions: Lämmchen