NOTICE:

If you have already read parts 1-3 of my Javascript Basics series of tutorials, then you are in the right place. Otherwise, I would advise that you briefly read over the previous tutorials to ensure that you understand them enough before reading this one.

 

Use the links below to read over the previous tutorials, even if you feel like you have a pretty good idea of how Javascript and HTML work, there may be information in them that you were not aware of. They are all worth reading.

 

Javascript Basics — Part 01 — Basic HTML and CSS

Javascript Basics — Part 02 — Basic Javascript Function Calls and Events

Javascript Basics — Level 3 — Simple Variables, Attributes, and Events


Using and Creating Functions

 

Javascript in general is made up of two main components: objects and functions. We will cover objects in the next tutorial, since they are more complex than functions. For now, lets talk about functions.

Functions are what gives Javascript the abiltiy to perform many different tasks by entering in a single command. Let me explain a little bit what I mean.. Lets start off with a basic HTML web page that has three separate paragraphs, one above the other with some basic text in them. The web page will also have a button called “Click Me” which will be used to call our functions that we are about to create.

So, here’s our starting page.

<html>
<head> <title> My Javascript Function Test Page </title> </head>
<body>

<p> Welcome to my test web page! </p>

<p> This is going to be the page where we will practice creating a few functions in this tutorial </p>

<p> By the end time we reach the end of the tutorial, this page will be much different. </p>

<button id="activate"> Click Here! </button>
</body>
</html>

 

Simple enough, right? You can just copy and paste the red code above into a blank file called

myPage.html

by using your favorite text editor. Once your finished, save it to your desktop.

This page is pretty boring as it stands right now, it has no CSS styling, layout, and the button that says Click Me doesn’t do anything. Well, thats all about to change. We’re going to create a Javascript function that will go through all of the paragraphs automatically, and change the CSS on each of them, all at the literal click of a button.

First, we need to make sure to start off our Javascript with the <script> tag. So, after the button’s close tag, but before the body’s close tag we’re going to put in our script tag. It will look just like this:

<p>  Welcome to my test web page! </p>

<p>  This is going to be the page where we will practice creating a few functions in this tutorial </p>

<p> By the end time we reach the end of the tutorial, this page will be much different. </p>

 

<button id="activate"> Click Here! </button>

 

<script type="text/javascript">
 
 
 </script> 

 

</body>

 

The next step is to create our function. This is done by simply entering the words function follwed by the name of the function, and any parameters we want to give to it. Lets call it change_css() for now. Soon we will discuss how to create more complex functions. Since we’re starting simple, we will call it change_css().

An important thing to notice is that there are no spaces in my function’s name. Functions cannot contain spaces or special characters, only letters, numbers, dashes, and underscores. The reason is because every other symbol is used for other things when it comes to Javascript.

Anyways, here’s how we create a new function: in the script area that we created, add in the following code:

<p> By the end time we reach the end of the tutorial, this page will be much different. </p>

<button id="activate"> Click Here! </button>

<script type="text/javascript">

function change_css() {

// Your code will be placed here

}

</script>

</body>


Now we have created the new function called change_css() .

Now anytime that you type in the words change_css() by itself, followed by a semi colon, like this:

change_css();

It will cause whatever code that we put in between the curley bracecs on our function to be executed. Let me see if I can show you a simple example of what I mean.

Remember the earlier tutorial where we created some simple Javascript onClick= attributes for a regular link? If not, go back to part 3 and re-read it until you understand it fully.

Well, we can use that same method on anything on the web page, including the body, p, and even button tags.So lets start out by adding in our onClick code and have it call the function.

<button id="activate" onClick="javascript: change_css();"> Click Here! </button>

<script type="text/javascript">

function change_css() {

// Your code will be placed here

}

</script>

Then, building upon the things we already learned from previous tutorials, we are going to introduce a few new javascript functions that are always available to use.

The first one is going to be getElementsByTagName() , which is used to automatically compile a list of all of the HTML tags which match a certain type. For our example, we’re going to use the <p> tag, since the goal of the function is to add CSS automatically to all of the paragraphs on the web page.

The way that use the getElementsByTagName() is by attaching it to the keyword: document , and then assigning the list to a variable. If none of this makes any sense to you, you probably didn’t read the previous tutorials closely enough, more specifically chapter 2 and 3, so go back and read them now.

So, the code to save a list of all of the <p> tags on the whole web page would look like this:

<script type="text/javascript">

 function change_css()   {
       
       var  myList =  document.getElementsByTagName("p");
 

}

</script> 

 

 

Next, we are going to use the for function to automatically go through the whole list, and change some CSS for each element in the list. Here’s how:


<script type="text/javascript">

function change_css()   {

     var  myList =  document.getElementsByTagName("p");


     for (var  x=0;  x < myList.length;  x++)  {

         myList[x].style.border = "2px solid black";

      }


}
</script> 

Since the code we put in literally makes no sense as of now, I’m going to break down each little part one at a time, and explain them all in full detail, so that you can walk away with a much better understanding of how Javascript, and other programming languages, work.

Lets start with that pesky for (var x=0; x<myList.length; x++) { line.

What this is basically doing is actually 4 different things in a single command. For starters, we are creating a variable called x and setting it to 0. This is represented as var x = 0;

Next, we are adding in a condition, basically saying x is less than myList’s length. Which is represented as x<myList.length;

Next, we are increasing the value of x by 1, represented by the x++; part.

What the for command does, is basically perform any action that is located in between the curley braces directly after the declaration.

So, if I added in the following code:

for (var   n =  1;    n <  20;    n++ )   {
     document.write(n);
     document.write("<br>");
}

 

 

The result would be this:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

The part that is in between the two curley braces:

 

  {

     myList[x].style.border = "2px solid black";

   }

 

 

Basically is just using the variable x to access each item from myList one at a time. The way that you access items that are in a list with Javascript is by using the [ ] symbols after the list’s name.

 

So, myList[x] actually represents whatever p element is in the x position from the front of the list.

If x were equal to 2, then myList[x] would refer to the 3rd paragraph on our web page.

(this is because items start at 0 in computer programming, not 1).

Finally, we set the CSS style for that element by using the same method described in previous tutorials.

 

Piece of cake.

 

Here’s a neat trick that uses the exact same method to make the 3 paragraphs all line up side by side when you click on the button:

Try changing the change_css() function to match the following code:

 

<script type="text/javascript">

    function change_css()   {
    
    
        document.body.style.display = "flex";
        document.body.style["flex-direction"] = "row";
        
        var  myList =  document.getElementsByTagName("p");
        
        for (var  x=0;  x < myList.length;  x++)  {
        
             myList[x].style.border = "2px solid black";
             myList[x].style["order"] = x;
        
        }
    }



</script> 

 

Once you have changed it, reload the file in your browser and click on the button.. You will see how just a couple of lines of code can do a whole lot.

 

In the next tutorial, we will talk about the other major part of Javascript: objects. In that one we will learn not only what objects are, but how to use them together with functions to create some pretty cool stuff.

 

 

Here’s the full code for the function demonstration page that we just made.

 

<html><head> <title>  My Javascript Function Test Page  </title>  </head><body>

<p>  Welcome to my test web page! </p>

<p>  This is going to be the page where we will practice creating a few functions in this tutorial </p>

<p> By the end time we reach the end of the tutorial, this page will be much different. </p>

 

<button id="activate" onClick="javascript: change_css();"> Click Here! </button>


<script type="text/javascript">
    function change_css()   {
    
    
        document.body.style.display = "flex";
        document.body.style["flex-direction"] = "row";
        
        var  myList =  document.getElementsByTagName("p");
        
        for (var  x=0;  x < myList.length;  x++)  {
        
             myList[x].style.border = "2px solid black";
             myList[x].style["order"] = x;
        
        }
    }



</script> 

 


</body></html>

 

14 Comments

  • After I initially commented I seem to have clicked the -Notify
    me when new comments are added- checkbox and now every time a comment is added I get 4 emails with
    the exact same comment. Perhaps there is a means you can remove me from that service?

    Thank you!

  • you are really a just right webmaster. The site loading speed is incredible.
    It seems that you’re doing any unique trick. Moreover, The contents
    are masterpiece. you’ve done a fantastic process in this matter!

    • I will be writing a new post named functions pt 2 which will dive into the symantics and use cases for functions

  • I love your blog.. very nice colors & theme. Did you create this website yourself
    or did you hire someone to do it for you? Plz answer back as I’m looking to create
    my own blog and would like to find out where u got this from.
    thanks a lot

  • Heya! I realize this is kind of off-topic however I had to ask.
    Does managing a well-established blog like yours require a lot of work?
    I am brand new to operating a blog but I do write in my
    diary on a daily basis. I’d like to start a blog
    so I can share my own experience and views online. Please let me know if
    you have any kind of ideas or tips for new aspiring blog owners.
    Appreciate it!

    • not really. running a blog is easy. All you need to have is a linux server, a configured http server, an ssl certificate, a mysql database installation, an ssh / sftp daemon, a bunch of virtual host configuration, a DNS server, a firewall, (probably want a docker container to run the public facing stuff), an email server, an smtp server, an IDS, a configured copy of wordpress, a variety of themes, and some content to put up (images and stuff)

      Not too hard.. 😉

Leave a Reply

Your email address will not be published. Required fields are marked *