Thursday, February 16, 2006

JavaScript Tutorial

 

JavaScript Tutorial

Javascript, what the heck is it? Is it a really difficult programming language that casual web designers should be afraid of? What is it used for? Hopefully we'll be able to answer these questions for you and more.

JavaScript has been around for several years now, in many different flavors. The main benefit of Javascript is to add additional interaction between the web site and its visitors at the cost of a little extra work by the web developer. Javascript allows industrious web masters to get more out of their website than HTML and CSS can provide.

By definition, Javascript is a client-side scripting language. This means the web surfer's browser will be running the script. This is opposite to client-side is server-side, which occurs in a language like PHP. These PHP scripts are run by the web hosting server.

There are many uses (and abuses!) for the powerful Javascript language. Here are a few things that you may or may not have seen in your web surfing days.

  • Clocks
  • Mouse Trailers (an animation that follows your mouse when you surf a site)
  • Drop Down Menus
  • Alert Messages
  • Popup Windows
  • HTML Form Data Validation

Tutorial Overview

Before you begin this tutorial you should have basic knowledge of HTML. Check out our Beginner and HTML tutorials to brush up on the basics.

This tutorial will cover the basics of Javascript, from where to place your Javascript all the way to making your own Javascript functions. Also there will be some good programming practice tips throughout this tutorial.

We recommend that you read a few lessons a day and practice what you have learned. This will help you to absorb the material more readily than if you blasted through the tutorial in one sitting!

How To Write Javascript

If you have ever used CSS before, then the whole part about how to include Javascript will be a lot simpler to grasp. Here are Tizag's three important steps you should always take when creating or using someone else's Javascript code.

  1. Use the script tag to tell the browser you are using Javascript.
  2. Write or download some Javascript
  3. Test the script!

There are so many different things that can go wrong with a script, be it human error, browser compatability issues, or operating system differences. So whenever using Javascript, be sure that you test your script out on a wide variety of systems and most importantly, different web browsers.

Your First Javascript Script

To follow the classic examples of many programming tutorials let's use Javascript to print out "Hello World" to the browser. I know this isn't very interesting, but it will be a good way to explain all the overhead required to do something in Javascript.

HTML & JavaScript Code:






Display:

Hello World!

Our first step was to tell the browser we were using a script with




Display:

We created a function called popup and placed it in the head of the HTML document. Now every time someone clicks on the button (this is an event) an alert will popup with "Hello World!". We will go into more depth on functions and events in a later lesson.

External Javascript Files

Having already dicussed placing Javascript in the head and body of your HTML document, let us now explore the third possible location, an external file. If you have ever used external CSS this lesson will be a cinch.

Importing an External Javascript File

Importing an external file is relatively painless. First the file you are importing must be valid Javascript, and only Javascript. Second, the file must have the extension ".js". Lastly, you must know the location of the file.

Let us assume we have a file "myjs.js" that contains a one line Hello World alert function. Also, let us assume that the file is the same directory as our HTML file we are going to code up. To import the file you would do the following in your HTML document.

HTML & JavaScript Code:









Display:

Great Javascript Repositories

There is a ton of great stuff you can do with Javascript, if you know how to code like Paul Allen and Bill Gates, but for the rest of us it is nice to get incredible Javascript tools without having to write them ourselves. Below are some of the better Javascript resources on the web these days.

External File Tips & Recap

  • Use external Javascript files when you want to use the same script on many pages, but don't want to have to rewrite the code on every page!
  • Use external Javascript files for including both types of scripts! The type that you place in the head (functions) and the type you place in the body (scripts you want to run when the page loads).
  • Be sure that your Javascript files (.js) do not include the

    Display:

    two plus ten = 12
    ten * ten = 100
    ten / two = 5

    Comparison Operators

    Comparisons are used to check the relationship between variables and/or values. A single equal sign sets a value while a double equal sign (==) compares two values. Comparison operators are used inside conditional statements and evaluate to either true or false.

    OperatorEnglish Example Result
    == Equal To $x == $y false
    != Not Equal To $x != $y true
    < Less Than $x < $y true
    > Greater Than $x > $y false
    <= Less Than or Equal To $x <= $y true
    >= Greater Than or Equal To $x >= $y false

    JavaScript Variables

    Variables in Javascript behave the same as variables in most popular programming languages (C, C++, etc) except that you don't have to declare variables before you use them. If you don't know what declaring is, don't worry about it, it isn't important!

    Javascript Using Variables

    A variable's purpose is to store information so that it can be used later. A variable is a symbolic name that represents some data that you set. To think of a variable name in real world terms, picture that the name is a grocery bag and the data it represents are the groceries. The name wraps up the data so you can move it around a lot easier, but the name is not the data!

    A Variable Example

    When using a variable for the first time it is not necessary to use "var" before the variable name, but it is a good programming practice to make it crystal clear when a variable is being used for the first time in the program. Here we are showing how the same variable can take on different values throughout a script.

    HTML & Javascript Code:




    Display:

    Hello World!
    I am learning javascript!
    Script is Finishing up...

    We made two variables in this example. One to hold the HTML for a line break and the other was a dynamic variable that had a total of three different values throughout the script.

    To assign a value to a variable you use the equal sign (=) with the variable on the left and the value to be assigned on the right. If you swap the order then your script will not work correctly! In english the Javascript "myVar = 'Hello World!'" would be: myVar equals 'Hello World!'.

    The first time we used a variable we placed var in front to signify its first use. In subsequent assignments of the same variable we did not need the var.

    Javascript Variable Naming Conventions

    When choosing a variable name you must first be sure that you do not use any of the Javascript reserved names Found Here . Another good practice is choosing variable names that are descriptive of what the variable holds. If you have a variable that holds the size of a shoe, then name it "shoe_size" to make your Javascript more readable.

    Finally, Javascript variable names may not start with a numeral (0-9). These variable names would be illegal: 7lucky, 99bottlesofbeer, and 3zacharm.

    A good rule of thumb is to have your variable names start with a lowercase letter (a-z) and use underscores to separate a name with multiple words (i.e. my_var, strong_man, happy_coder, etc).

    Javascript Functions

    If you have any programming experience, then you do not need to spend much time on this lesson. Functions in Javascript behave similar to numerous programming languages (C, C++, PHP, etc). If this is your first time learning about functions, then be sure to go through this lesson very thoroughly as a solid understanding of functions will make the rest of this tutorial much easier to follow.

    What's a Function?

    A function is a piece of code that sits dormant until it is referenced or called upon to do its "function". In addition to controllable execution, functions are also a great time saver for doing repeatable tasks.

    Instead of having to type out the code every time you want something done, you can simply call the function multiple times to get the same effect. This benefit is also known as "code reusability".

    Example Function in Javascript

    A function does not execute when the page loads and so it should be placed inside the head of your HTML document. Creating a function is really quite easy, all you have to do is tell the browser you're making a function, give the function a name, and then write the Javascript like normal. Below is the example alert function from the previous lesson.

    HTML & Javascript Code:








    Display:

    We first told the browser we were going to be using a function by typing "function". Next, we gave our function a name, so that we could use it later. Since we are making a pop up alert, we called our function "popup".

    The curly braces "{,}" define the boundaries of our function code. All popup function code must be contained within the curly braces.

    Something that might be slightly confusing is that within our "popup" function we use another function called "alert" which brings up a popup box with the text that we supply it. It is perfectly OK to use functions within functions, like we have done here. Furthermore, this is one of the great things about using functions!

    What we didn't talk about was how we got this function to execute when the button is clicked. The click is called an event, and we will be talking about how to make functions execute from various types of events in the next lesson.

    Events in Javascript

    The absolute coolest thing about Javascript is the ability to create dynamic web pages that increase user interaction, making the visitor feel like the website is almost coming alive right before their eyes.

    The building blocks of an interactive web page is the Javascript event system. An event in Javascript is something that happens with or on the web page. A few example of events:

    • A mouse click
    • The web page loading
    • Mousing over a hot spot on the web page, also known as hovering
    • Selecting an input box in an HTML form
    • A keystroke

    A Couple of Examples Using Events

    Javascript has predefined names that cover numerous events that can occur, including the ones listed above. To capture an event and make something happen when that event occurs you must specify the event, the HTML element that will be waiting for the event, and the function(s) that will be run when the event occurs.

    We have used a Javascript event in a previous lesson, where we had an alert popup when the button was clicked. This was an "onclick" Javascript event. We will do that same example again, as well as the mouseover and mouseout events.

    HTML & Javascript Code:









    Hover Me!



    Display:

    With the button we used the event onClick event as our desired action and told it to call our popup function that is defined in our header. To call a function you must give the function name followed up with parenthesis "()".

    Our mouseover and mouseout events were combined on one HTML element, a link. We wanted to do nothing when someone put their mouse on the link, but when the mouse leaves (onMouseout) we displayed a popup.

    Javascript Statements

    All the Javascript code that you will write will, for the most part, be comprised of many separate statements. A statement is setting a variable equal to a value. A statement is also a function call, i.e. document.write(). Statements define what the script will do and how it will be done.

    Typical Ending of a Statement

    In typical programming languages like C and PHP, the end of a statement is marked with a semicolon(;), but we have seen that the semicolon is optional in Javascript. In Javascript the end of a statement is most often marked by starting a new line.

    Categories of Statements

    In addition to the standard statements like changing a variable's value, assigning a new value, or calling a function, there are groups of statements that are distinct in their purpose. We will provide a brief overview of each of these categories in this lesson and cover them in greater detail later in the tutorial.

    • Conditional Statements
    • Loop Statements
    • Object Manipulation Statements
    • Comment Statements
    • Exception Handling Statements

    Conditional Statements

    If you were to win a $100 million lottery then you would probably quit your job. That last statement is a conditional if/then statement that is used a great deal in programming. If some condition (winning the lottery) is true, then something happens (you quit your job). If the condition is false, then you probably will not take that action (quit your job).

    Conditional statements are used to control your scripts so that different actions can be taken depending on the situation. You may want to display a special image on your home page during the holidays. This condition would depend on what day it was, and if it was a holiday, then a special holiday image would be displayed to your visitors. Without proper knowledge of the conditional statement your scripts will not be as lively or dynamic as they could possibly be.

    Loop Statements

    Have you ever had to send out marriage announcements? If not, this is how it goes. You take the invitation, place it in the envelope, lick the envelope, seal the envelope, then send it off. Then you take the next invitation off the stack of 99 remaining invitations, place it in an envelope, lick the envelope, seal... You get the idea! It is a boring, repetitive task!

    Wouldn't it be great if there was an easier way? Well in programming and in Javascript there is. The process is called "looping" and it will turn your cute little scripts into massive work horses with the right planning.

    A loop statement checks to see if some condition is true, say our condition is "Are there any invitations left?" and if that condition is true it will execute a chunk of code. Our code in this example would be to stuff, lick, and seal the envelope. After the code is executed the condition is checked again, if it is true then the process begins again, if it is false, then the loop code stops execution and the script continues along.

    Believe me when I say this is something you want to learn more about!

    Object Manipulation Statements

    These are statements that are used to take advantage of the object model to get tasks done. If you do not know about the object model at this time, do not worry. We will be talking about it later.

    Comment Statements

    Comment statements are used to prevent the browser from executing certain parts of code that you designate as non-code. Why would you want to do this? There are many reasons. By disallowing the block of text to be read you can then place in comments for yourself, much like HTML comments, and you can also block out segments of your code for whatever reason you may have.

    The single line comment is just two slashes (//) and the multiple line comment starts with (/*) and ends with (*/). We will talk about comments in greater depth in a later lesson.

    Exception Handling Statements

    Sometimes when you are programming you do not know for sure if the file that you will be writing to, the input stream you are reading from, or the connection you have established will be usable for the code that you want to execute. There is a way to program safety mechanisms, so that your code handles common problems that may arise (maybe the input stream you are reading from suddenly disappears).

    The try...catch statement tries to execute a piece of code and if it fails the catch should handle the error gracefully. This is an advanced programming subject that is interesting, but not necessary for the majority of Javascript programmers.

    Wrapup

    I hope you found this overview of Javascript statements interesting. Do not despair if you have not grasped all the details discussed above, as we will be covering them further in a later lesson.

    Javascript If Statement

    As your Javascript programs get more sophisticated you will need to make use of conditional statements that allow your program to make decisions. Nearly all other programming languages use conditionals and Javascript is no exception.

    The If Statement is a way to make decisions based on a variable or some other type of data. For example you might have a variable that stores the date. With this tiny bit of information you could easily program a small script to print out "Today is my Birthday!" whenever the day and month were equal to your birthday.

    This lesson will teach you the basics of using an If Statement in Javascript.

    Javascript If Statement Syntax

    There are two major parts to an if statement: the conditional statement and the code to be executed.

    The conditional statement is a statement that will evaluate to either True or False. The most common type of a conditional statement used is checking to see if something equals a value. An example would be checking if the date equaled your birthday.

    The code to be executed contains the Javascript code that will be executed only if the If Statement's conditional statement was true. In this simple If Statement example we print out a message if the variable we are checking is equal to 7.

    Javascript Code:

    Display:

    Lucky 7!

    This simple example created myNum and set it to 7. We then checked to see if myNum was equal to 7 "myNum == 7" in the If Statement's conditional statement which evaluated to True.

    Because the conditional statement was True the block of code associated with our If Statement "document.write..." was executed, as you can see in the Display.

    Javascript If Statement: Else

    We already taught you how to execute code if a given condition is True, but what if you want to execute another piece of code if something is False? The answer is to use an extension to the If Statement; the Else clause.

    The Else clause is executed when the conditional statement is False. Let's take our example from above, add an Else clause and change the value of myNum so that our conditional statement is False.

    Javascript Code:

    Display:

    You're not very lucky today...

    Javascript Else If Statement

    In the previous lesson you learned how to create a basic If Statement in Javascript, which is good enough for most programming situations. However, sometimes it is helpful to have the ability to check for more than one condition in a single If Statement block.

    The Else If statement is an extension to the If Statement that allows you to create as many checks (conditional statements) as you want.

    Javascript Else If Example

    Imagine that you want to have a small "student" script that will print out a customized message depending who is accessing the web page. If you had more than two custom messages you could use the Else If extension to solve this programming problem.

    Javascript Code:

    Display:

    What stink bombs?

    There are two important things to note about the Else If extension:

    1. You must have a normal If Statement before you can use the Else If statement. This is because the Else If statement is an addon to the If Statement.
    2. YOu can have multiple Else If add-ons. In our example we only used one Else If extension, but you can add as many as you require.

    Javascript While Loop

    The while loop is an advanced programming technique that allows you to do something over and over while a conditional statement is true. Although the general uses of the while loop are usually a bit complex, this lesson will teach you the basics of how to create a while loop in Javascript.

    Javascript While Loop Explained

    There are two key parts to a Javascript while loop:

    1. The conditional statement which must be True for the while loop's code to be executed.
    2. The while loop's code that is contained in curly braces "{ and }" will be executed if the condition is True.

    When a while loop begins the Javascript interpreter checks the condition statement is true. If it is the code between the curly braces is executed. At the end of the code segment "}" the while loop loops back to the condition statement and begins again.

    If the condition statement is always True then you will never exit the while loop, so be very careful when using while loops!

    Creating a Simple While Loop

    This example shows how to create a basic while loop that will execute a document.write 10 times and then exit the loop statement.

    Javascript Code:

    Display:

    While loop is beginning
    myCounter = 0
    myCounter = 1
    myCounter = 2
    myCounter = 3
    myCounter = 4
    myCounter = 5
    myCounter = 6
    myCounter = 7
    myCounter = 8
    myCounter = 9
    While loop is finished!

    Our variable myCounter started off at 0, which is less than 10, so our while loop executed its code. The value 0 was printed to the browser and then myCounter was incremented by 1 and the while loop started over again.

    1 was less than 10 so the while loop's code was executed...and the process repeats itself a few more times until...

    myCounter was 10 which was not less than 10 so the while loop's code did not execute. You can see this in the Display: because the last value to be printed out was 9.

    Note: Advanced programmers may recognize that a for loop would be a better solution for this example, but we hope you can ignore this for our needs to create an easy example!

    Javascript For Loop

    The Javascript For Loop resembles the for loop you might have seen in many other programming languages. It is used when you need to do a set of operations many times, with an increment of some kind after each run through the block of code.

    If you have read the previous lesson Javascript While Lesson then this should be a cinch.

    Javascript For Loop Explained

    There are four important aspects of a Javascript for loop:

    1. The counter variable is something that is created and usually used only in the for loop to count how many times the for loop has looped.
    2. The conditional statement that decides whether the for loop continues executing or not. This check usually includes the counter variable in some way.
    3. The counter variable is incremented after every loop in the increment section of the for loop.
    4. The code that is executed for each loop through the for loop.

    This may seem strange, but 1-3 all occur on the same line of code. This is because the for loop is such a standardized programming practice that the designers felt they might as well save some space and clutter when creating the for loop.

    Javascript For Loop Example

    This example will show you how to create a simple for loop that prints out the value of our counter until the counter reaches 5. Pay special close attention to the three different items that are on the first line of the for loop code. These are the important for loop parts 1-3 that we talked about earlier.

    Javascript Code:

    Display:

    For loop code is beginning
    Counter i = 0
    Counter i = 1
    Counter i = 2
    Counter i = 3
    Counter i = 4
    For loop code is finished!

    The counter variable name i may seem a little strange, but it has been used for years now that you might as well get used to it as the default for loop counter. Other common variable names are j, k, x and y

    So in this example our counter was initially set to 0 with "i = 0;" and then the conditional statement "i <>for loop's code was executed.

    After the loop's code had been executed then the increment "i++" happens, making the counter i equal to 1. The for loop then checked that i was less than 5, which it was, resulting in the loop's code being executed again.

    This looping happened a couple more times until i was equal to 5, which is not less than 5 and the for loop stopped executing.

    For loops may seem very confusing at first, but let me assure you, they are quite useful and should be studied thoroughly by anyone who wishes to become a intermediate programmer.

    Javascript Comments

    Have you ever written a script or a program in the past only to look at it 6 months later and have no idea what's going on in the code? You probably forgot to do what all programmers tend to forget: write comments!

    When writing code you may have some complex logic that is confusing, this is a perfect opportunity to include some comments in the code that will explain what is going on. Not only will this help you remember it later on, but if you someone else views your code they will also be able to understand the code (hopefully)!

    Another great thing about comments is the ability for comments to remove bits of code from execution when you are debugging your scripts. This lesson will teach you how to create two types of comments in Javascript: single line comments and multi-line comments.

    Creating Single Line Comments

    To create a single line comment in Javascript you place two slashes "//" in front of the code or text you wish to have the Javascript interpreter ignore. When you place these two slashes, all text to the right will be ignored, until the next line.

    These types of comments are create for commenting out single lines of code and writing small notes.

    Javascript Code:

    Display:

    I have comments in my Javascript code!

    Each line of code that is colored red is commented out and will not be interpreted by the Javascript engine.

    Creating Multi-line Comments

    Although a single line comment is quite useful, it can sometimes be burdensome to use for large segments of code you wish to disable or extra long winded comments you need to insert. For this large comments you can use Javascript's multi-line comment that begins with /* and ends with */.

    Javascript Code:

    Display:

    I have multi-line comments!

    Quite often text editors have the ability to comment out many lines of code with a simple key stroke or option in the menu. If you are using a specialized text editor for programming be sure that you check and see if it has an option to easily comment out many lines of code!

    Javascript Array

    An array is a variable that can store many variables. Many programmers have seen arrays in other languages and they aren't that different in Javascript.

    The following points should always be remembered when using arrays in Javascript:

    • The array is a special type of variable.
    • Values are stored into an array by using the array name and by stating the location in the array you wish to store the value in brackets.
      Example:
      myArray[2] = "Hello World";
    • Values in an array are accessed with the array name and location of the value.
      Example:
      myArray[2];
    • Javascript has built in functions for arrays, so check out these built in array functions before writing code yourself!

    Creating a Javascript Array

    Creating an array is slightly different than creating a normal variable. Because Javascript has variables and properties associated with arrays, you have to use a special function to create a new array. This example shows how you would create a simple array, store values to it and access these values.

    Javascript Code:

    Display:

    FootballBaseballCricket

    Notice that you set values and get values from an array by specifying the position, in brackets, of the value you want to use.

    Javascript Array Sorting

    Imagine that you wanted to sort an array alphabetically before you wrote the array to the browser. Well, this code has already been written and can be accessed by using the Array'ssort method.

    Javascript Code:

    Display:

    BaseballCricketFootball

    Javascript Array: Other Resources

    Arrays are a very complex area of programming, especially in Javascript. This lesson could not possible cover all the areas of Javascript arrays, but we have compiled some useful resources for you to check out!


    Javascript Alert - What is it?

    If you do not have Javascript enabled on your web browser, then you may have been able to avoid them in your internet history. The Javascript alert is a dialogue box that pops up and takes the focus away from the current window and forces the web browser to read the message. View an alert message.

    You may have noticed that you didn't get a Javascript alert popup when you came to this page. That is because doing so would be in bad taste for a web designer. You see, alerts should be very, very rarely used and even then these following guidelines should be considered when using them.

    When to Use Popups / Alerts

    Javascript alerts are ideal for the following situations:

    • If you want to be absolutely sure they see a message before doing anything on the website.
    • You would like to warn the user about something. For example "the following page contains humor not suitable for those under the age of 14."
    • An error has occurred and you want to inform the user of the problem.
    • When asking the user for confirmation of some action. For example they have just agreed to sign over the deed to their house and you want to ask them again if they are absolutely positive they want to go through with this decision!

    Even though the above situations would all be valid times to use the alert function, you could also skip the alert and just have the error message, confirmation, etc displayed in plain HTML, instead of in a popup. More and more bigger sites are opting to lose the Javascript alerts and instead keep everything in HTML.

    Coding a Simple Javascript Alert

    Just for fun, let us suppose that we are making an alert for some website that asks people to hand over the deed to their house. We need to add an alert to be sure these people are in agreement. The following code will add an alert by using an HTML button and the onClick event.

    HTML & Javascript Code:



    Display:

    The string that appears between the single quotes is what will be printed inside the alert box when the user clicks on the button. If the HTML Forms is confusing to you, be sure to brush up on our HTML Forms Lesson. Continue the tutorial to learn more about the different kinds of Javascript pop ups that are at your disposal.

    Javascript Confirm

    The Javascript confirm function is very similar to the Javascript alert function. A small dialogue box pops up and appears in front of the web page currently in focus. The confirm box is different than the alert box in that it supplies the user with a choice, they can either press OK to confirm the popups message or they can press cancel and not agree to the popups request.

    Confirmation are most often used to confirm an important action that is taking place on a website. For example they may be about to submit an order or about to visit a link that will take them away from the current website.

    Javascript Confirm Example

    Below is an example of how you would use a confirm dialogue box to warn the user about something, and they could either continue on or stay put.

    HTML & Javascript Code:












    Display:


    Note the part in red, this is where all the magic happens. We call the confirm function with the message, "Leave Tizag?". Javascript then makes a popup window with two choices and will return a value to our script code depending on which button the user clicks.

    Confirm returns the value 1 if the user clicks OK and the value 0 if the user clicks Cancel. We store this value in answer by setting it equal to the confirm function call.

    After answer has stored the value, we then use answer as a conditional statement. If answer is anything but zero, then we are going to send the user away from Tizag.com. If answer is equal to zero, then we will keep the user at Tizag.com because they clicked the Cancel button.

    In either case we have a Javascript alert box that appears to inform the user what is going to happen. "Bye bye!" if they chose to leave and "Thanks for sticking around!" if they chose to stay.

    In this lesson we also used the window.location property for the first time. Whatever we set window.location to will be where the browser is redirected to. In this example we chose Google.com. We will discuss redirection in greater detail later on.

    Javascript Prompt

    The Javascript prompt is a relic from the 1990's that you seldom see being used in modern day websites. The point of the Javascript prompt is to gather information from the user so that it can be used throughout the site to "personalize" it for the visitor.

    Back in the day you'd often see these prompts on personal web pages asking for your name. After you typed in the information you would be greeted with a page that had a welcome message, such as "Welcome to My Personal Web Page John Schmieger!" (If you name just happened to be John Schmieger).

    The Javascript prompt is not very useful and many find it slightly annoying, but hey, this tutorial is here to educate you, so let's learn how to make that prompt!

    Simple Javascript Prompt

    You can use a prompt for a wide variety of useless tasks, but below we use it for an exceptionally silly task. Our prompt is used to gather the user's name to be displayed in our alert dialogue box.

    HTML & Javascript Code:







    Display:

    Recap on Javascript Prompt

    It sure is a quick way to gather some information, but it is not as a reliable information gatherer as the other options available to you. If you want to find out someone's name and information, the best way to request this information would be to use HTML Forms. And if you wanted to use the information throughout the website, you might use some PHP to get that job done in a more sophisticated manner.

    Javascript Print Function

    The Javascript print function performs the same operation as the print option that you see at the top of your browser window or in your browser's "File" menu. The Javascript print function will send the contents of the webpage to the user's printer.

    Many believe this function to be worthless, but there are many computer users that do not know their way around a computer all that well and it can sometimes create a more user friendly experience when you provide as many helpful features as possible.

    Javascript Print Script - window.print()

    The Javascript print function window.print() will print the current web page when executed. In this example script we will be placing the function on a Javascript button that will perform the print operation when the onClick event occurs.

    HTML & Javascript Code:



    Display:

    If you click this button you should be prompted with whatever application your computer uses to handle the printing functions.

    JavaScript Redirect

    You're moving to a new domain name. You have a time-delay in place on your download site. You have a list of external web servers that are helping to mirror your site. What will help you deal and/or take advantage of these situations? Javascript redirects will.

    When a web page is moved will most probably would like to place a "redirect" page at the old location that informs the visitor of the change and then after a timed delay, will forward the visitor to the new location. With the javascript redirection, you can do just this.

    Javascript Window.Location

    The control over what page is loaded into the browser rests in the javascript propety window.location, by setting this equal to a new URL you will in turn change from the current web page to the one that is specified. If you wanted to redirect all your visitors to www.google.com when they arrived at your site you would just need the script below:

    HTML & Javascript Code:


    Javascript Time Delay

    Implementing a timed delay in javascript is useful for the following situations:

    • Showing an "Update your bookmark" page when you have to change URLs or page locations
    • For download sites that wish to have a few second delay before the page loads and when the download starts
    • To refresh a web page every specified amount of seconds

    The code for this timed delay is slightly involved and is beyond the scope of this tutorial. However, we have tested it and it seems to function properly.

    HTML & Javascript Code:






    Prepare to be redirected!


    This page is a time delay redirect, please update your bookmarks to our new location!




    View Page:

    The most important part of getting the delay to work is being sure to use the javascript function setTimeout. We want the delayer() function be used after 5 seconds or 5000 miliseconds, so we pass the setTimeout() two arguments.

    • 'delayer()' - The function we want setTimeout() to execute after the specified delay.
    • 5000 - the number of milisecods we want setTimeout() to wait before executing our function. 1000 miliseconds = 1 second.

    Web Page Redirection

    Do use javascript for redirections when you change your website's URL or move a file to a new location. Don't use redirections when they could easily be replaced with a normal HTML hyperlink.

    Javascript Popups

    Chances are if you are reading this web page then you have experienced hundreds of Javascript popup windows throughout your web surfing lifetime. Want to dish out some pain of your own creation onto unsuspecting visitors? I hope not! Because web sites with irrelevant popups are bad!

    However, we will show you how to make windows popup for reasonable occasions, like when you want to display extra information, or when you want to have something open a new window that isn't an HTML anchor tag .

    Javascript window.open Function

    The window.open() function creates a new browser window, customized to your specifications, without the use of an HTML anchor tag. In this example we will be making a function that utilizes the window.open() function.

    HTML & Javascript Code:

    Display:

    This works with pretty much any tag that can be clicked on, so please go ahead an experiment with this fun little tool. Afterwards, read on to learn more about the different ways you can customize the Javascript window that POPS up.

    Javascript Window.Open Arguments

    There are three arguments that the window.open function takes. First the relative or absolute URL of the web page to be opened. Secondly, a text name for the window, and lastly a long string that contains all the different properties of the window.

    Naming a window is very useful if you want to manipulate it later with Javascript. However, this is beyond the scope of this lesson and we will instead be focusing on the different properties you can set with your brand spanking new Javascript window. Below are some of the more important properties.

    Dependent, fullscreen, resizable, and status are all examples of ON/OFF properties. You can either set them equal to zero to turn them off, or set them to one to turn them ON. There is no inbetween setting for these types of properties.

    Upgraded Javascript Popup Window!

    Now that we have the tools, let's make a sophisticated Javascript popup window that we can be proud of.

    HTML & Javascript Code:

    Display:

    Now that is a prime example of a worthless popup! When you make your own, try to have them relate to your content, like a small popup that has no navigation that just gives the definition or explanation of a word, sentence, or picture!

    Javascript Date and Time Object

    The Date object is useful when you want to display a date or use a timestamp in some sort of calculation. In java you can either make a Date object by supplying the date of your choice, or you can let Javascript create a Date object based on your visitor's system clock. It is usually best to let Javascript simply use the system clock.

    When creating a Date object based on the computer's (not web server's!) internal clock, it is important to note that if someone's clock is off by a few hours or they are in a different time zone, then the Date object will create a different time than the one created with your own computer.

    Javascript Date Today (Current)

    To warm up our Javascript Date object skills, let's do something easy. If you do not supply any arguments to the Date constructor (this makes the Date object) then it will create a Date object based on the visitor's internal clock.

    HTML & Javascript Code:

    Display:

    Nothing shows up! That's because we still don't know the methods of the Date object that let us get the information we need(i.e. Day, Month, Hour, etc).

    Get the Javascript Time

    The Date object has been created and now we have a variable that holds the current date. To get the information we need to print out the date we have to utilize some or all of the following functions:

    Now we can print out the date information. We will be using the getDate, getMonth, and getFullYear methods in this example.

    HTML & Javascript Code:

    Display:

    Notice that we added 1 to the month variable to correct the problem with January being 0 and December being 11. After adding 1 January will be 1 and December will be 12.

    Javascript Current Time Clock

    Now instead of displaying the date we will display the format you might see on a typical digital clock HH:MM AM/PM (H = Hour, M = Minute).

    HTML & Javascript Code:

    Display:

    We check to see if hours or minutes is less than 10, if it is then we need to add a zero to the beginning of minutes. This is not necessary, but if it is 1:01 AM then our clock would output "1:1 AM", which doesn't look very nice at all!

    Javascript Form Validation

    There's nothing more troublesome than receiving orders, guestbook entries, or other form submitted information that is incomplete in some way. You can avoid these headaches once and for all with Javascript's amazing way to combat bad form data with a technique called "form validation".

    The idea behind Javascript form validation is to provide a method to check the user entered information before they can even submit it. Javascript also lets you display helpful alerts to inform the user what information they have entered incorrectly and how they can fix it. In this lesson we will be reviewing some basic form validation, namely checking to see if a field is empty or not.

    Form Validation - Checking for Non-Empty

    This is the easiest and least thorough way of form validation. You want to be sure that your visitors enter data into the HTML fields you have "required" for a valid submission. Below is the Javascript code to perform this basic check. We'll see how to use it in our form later.

    Javascript Code:

    This function takes one argument, elem. This parameter elem will be coming from an input within our HTML form. To get the value from an input you use inputVariable.value. In our example inputVariable is equal to elem. We set our string variable str equal to elem.value to store this value.

    Javascript strings have built in properties, one of which is the length property which returns the length of the string. If the string length is equal to zero, then we know that the user did not enter any information into the field. If this is the case then we give them an alert message to inform them of their error.

    Batch Form Validation - How To

    Now that we have this non-empty validation function, how are we going to use it? There are two opportune times to perform these validation checks: when the user changes from one field to another and when the user submits the data. The Javascript events systems has names for these cases and they are: onBlur and onSubmit.

    In this lesson we will be focusing on the onSubmit event because it is the most commonly accepted time for validation. We are going to create a master function whose only purpose is to call other functions which do the actual checks to see if the form data is valid. Here is our master function.

    Javascript Code:

    function formValidation(form){
    if(notEmpty(form.req1)){
    if(notEmpty(form.req2)){
    return true;
    } } else {
    return false;
    }
    }

    Our master function is rightly named "formValidation" and takes one argument that represents the form we are checking to see if it is valid. Form input fields can be accessed by using their name. We are going to be naming our text fields req1 and req2, so we used form.req1 and form.req2 for passing arguments to our non-empty function.

    As you can see, our HTML form is going to be validating two required fields: req1 and req2. If both of these text fields pass the non-empty test then we will return true and submit the data. However, if it returns false then that means the user will see a Javascript alert error message and no data will be submitted.

    The Whole Shebang!

    Now that we have all the Javascript done, we just need to fill in the HTML. The validation will occur when the user submits the data and so we will use the onSubmit event to execute our master function.

    HTML & Javascript Code:






    Required 1:

    Required 2:





    Display:

    Required 1:
    Required 2:
    If formValidation(this) returns false then the form will not submit. If it returns true then the data will submit. Test out this script on your own, and try to add another required field "req3" and check to see that it is non-empty as well

    Javascript Void 0

    Hyperlinks like this one entice visitors to click because they know it will lead to a new page. However, sometimes when you are making a script you would like to add functionality to your web site that lets a hyperlink to be clicked, perform a useful action like update the sums on the web page, but not load a new page.

    It are these types of programming solutions that will utilize the Javascript Void 0 programming tool. This lesson will teach you some of the reasons to use the Javscript Void 0 programming strategy in your scripts.

    Directly Executing Javascript in a Browser

    Web browsers allow you to execute Javascript statements directly by entering Javascript code into the browser's URL text field. All you need to do is place a Javascript: before your code to inform the browser you wish to run Javscript. You can play around with this right now by typing something like

    • Javascript:alert("I'm learning at Tizag.com")

    into the browser's URL text field and pressing Enter.

    This is useful to you, the Javascript scripter, because you can now set your hyperlinks's href attribute equal to a Javscript statement! This means you can remove the hyperlink's ability to load a new page and reprogram it to do your "complete some actions directly on this page" bidding.

    This practice can be seen in services like Gmail (Google Email) which does a great deal of interaction with hyperlinks, but very few new pages loading. Here is an example link that does not load a new web page.

    Javascript Code:

    Display:

    This is interesting to learn and has limited uses, but the true power of direct URL Javscript statements is only unleashed when you can return a value from these statements. That is where the void 0 comes in.

    Javascript Void 0 Explanation

    Web browsers will try and take whatever is used as a URL and load it. The only reason we can use a Javscript Alert statement without loading a new page is because alert is a function that returns a null value. This means that when the browser attempts to load a new page it sees null and has nothing to load.

    The important thing to notice here is that if you ever do use a Javascript statement as the URL that returns a value the browser will attempt to load a page. To prevent this unwanted action you need to use the void function on such statement, which will always return null and never load a new page.

    Simple Javscript Void 0 Simple Example

    Void is an operator that is used to return a null value so the browser will not be able to load a new page. An important thing to note about the void operator is that it requires a value and cannot be used by itself. Here is a simple way to use void to cancel out the page load.

    Javascript Code:

    Display:

    Simple Javscript Void 0 Useful Example

    This example shows how you would return a value using the void operator. myNum is a variable that we set to the value 10. We then use the same variable myNum in an alert operation.

    Javascript Code:

    Display:




  posted by Smile Community @ 8:11 PM

0 Comments:

Post a Comment

<< Home

 

Search


Web W-master

Home

Previous Post

*HTML Tutorial

*PHP Tutorial

*Google Adsense

*E-mail Utilities

*Promotion Tools

*HTML Editors

*Blog Tools

*WELCOME

Archives

*February 2006

*March 2006

*April 2006

*May 2006

*August 2006

*September 2006

*October 2006

*November 2006

*December 2006

Partner Links

Best Offers

RSS Feeds

TOP Blog Links

BlogOmg >> The Best and Most Popular Blogs
Ping Your Blog!
Name:
URL:
Powered By: PingTheEmpire.com