javascript
JavaScript has been around for several years now, in many
different flavors. The main benefit of Javascript is to add additional
interaction between the website and its visitors with just 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. The opposite of
client-side is server-side, which occurs in a language like PHP. 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
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:
Our first step was to tell the
browser we were using a script with the
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 file 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 the HTML file we are going
to code up. To import the file you would do the following in your HTML
document.
File myjs.js Contents:
function popup() {
alert("Hello World")
}
HTML & JavaScript Code:
javascript arithmetic operator chart
Operator
|
English
|
Example
|
+
|
Addition
|
2 + 4
|
-
|
Subtraction
|
6 - 2
|
*
|
Multiplication
|
5 * 3
|
/
|
Division
|
15 / 3
|
%
|
Modulus
|
43 % 10
|
Modulus % may be a
new operation to you, but it's just a special way of saying "finding the
remainder". When you perform a division like 15/3 you get 5, exactly.
However, if you do 43/10 you get an answer with a decimal, 4.3. 10 goes into 40
four times and then there is a leftover. This leftover is what is returned by
the modulus operator. 43 % 10 would equal 3.
javascript operator example with variables
Performing operations on
variables that contain values is very common and easy to do. Below is a simple
script that performs all the basic arithmetic operations.
HTML & JavaScript Code:
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:
example function in javascript
A function that does not execute
when a page loads 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:
events
in javascript
The absolute coolest thing about JavaScript is its ability to help
you create dynamic webpages that increase user interaction, making the visitor
feel like the website is almost coming alive right before her 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 webpage. A few example of events:
- A mouse click
- The webpage loading
- Mousing over a hot spot on the webpage, 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!
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 be either True or False. The most common type
of conditional statement used checks to see if something equals a value. An
example would be checking if a date equals your birthday.
Below is a segment of JavaScript
code that will be executed only if the If Statement's conditional statement is
true. In this simple If
Statement example, we print
out a message if the variable we are checking is equal to 7.
JavaScript Code:
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 myNumso that our conditional
statement is False.
JavaScript Code:
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 webpage. If you have more than two custom
messages, you could use the Else
If extension to solve this
programming problem.
JavaScript Code:
creating a simple while loop
This example shows how to create
a basic while loop that will execute adocument.write 10 times and then exit the loop
statement.
JavaScript Code:
creating multi-line comments
Although a single line comment is
quite useful, it can sometimes be burdensome to use when disabling long
segments of code or inserting long-winded comments. For this large comments you
can use JavaScript's multi-line comment that begins with /* and ends with */.
JavaScript Code:
creating a javascript array
Creating an array is slightly
different from 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:
coding a simple javascript alert
Just for fun, let's 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:
"alert('Are you sure you want to give us the deed to your house?')"
value="Confirmation Alert">
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:
javascript print script - window.print()
The JavaScript print function window.print() will print the current webpage 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:
javascript window.location
Control over what page is loaded
into the browser rests in the JavaScript property window.location. By setting window.location equal to a new URL, you will in turn
change the current webpage 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 in 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 timed delay before the download starts
- To refresh a webpage once every specified number 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!
The most important part of getting the delay to work is being sure
to use the JavaScript function setTimeout. We want the delayer() function to be used after 5 seconds or 5000
milliseconds (5 seconds), so we pass the setTimeout() two arguments.
- 'delayer()' - The function we want setTimeout() to execute after the specified delay.
- 5000 - the number of millisecods we want setTimeout() to wait before executing our function. 1000 miliseconds = 1 second.
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.
CLICK ME TOO!
javascript window.open arguments
There are three arguments that
the window.open function takes:
1.
The relative or absolute URL of
the webpage to be opened.
2.
The text name for the window.
3.
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 - Subwindow closes if the parent window (the window that opened it) closes
- fullscreen - Display browser in fullscreen mode
- height - The height of the new window, in pixels
- width - The width of the new window, in pixels
- left - Pixel offset from the left side of the screen
- top - Pixel offset from the top of the screen
- resizable - Allow the user to resize the window or prevent the user from resizing, currently broken in Firefox.
- status - Display or don't display the status bar
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!
CLICK ME TOO!
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, we have to utilize some or all of the following
functions:
- getTime() - Number of milliseconds since 1/1/1970 @ 12:00 AM
- getSeconds() - Number of seconds (0-59)
- getMinutes() - Number of minutes (0-59)
- getHours() - Number of hours (0-23)
- getDay() - Day of the week(0-6). 0 = Sunday, ... , 6 = Saturday
- getDate() - Day of the month (0-31)
- getMonth() - Number of month (0-11)
- getFullYear() - The four digit year (1970-9999)
Now we can print out the date
information. We will be using the getDate,getMonth,
and getFullYear methods in this example.
It is now
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).
It is now
string length property
The length property returns the number of
characters that are in a string, using an integer. Below is the basic code for
accessing this property.
var myString = "123456";
var length = myString.length;
document.write("The string is this long: " + length);
// Same thing, but using the property inside the write function
document.write("
The string is this long: " + myString.length);
string changed? length might change
If you were to reference the length property after concatenating (adding)
some characters to the string, then the length property will reflect these
changes. Think of this as a friendly reminder to only check the length of the
string after you are sure it isn't going to be changed.
var myString = "123456";
document.write("The string is this long: " + myString.length);
myString = myString + "7890";
document.write("
The string is now this long: " + myString.length);
simple split function example
Let's start off with a little
example that takes a string of numbers and splits when it sees the number 5.
That means the delimiter for this example is 5. Notice that the split function returns an array that we store into mySplitResult.
var myString = "123456789";
var mySplitResult = myString.split("5");
document.write("The first element is " + mySplitResult[0]);
document.write("
The second element is " + mySplitResult[1]);
arger split function example
Below we have created a split example to illustrate how this
function works with many splits. We have created a string with numbered words
zero through four. The delimiter in this example will be the space
character " ".
var myString = "zero one two three four";
var mySplitResult = myString.split(" ");
for(i = 0; i < mySplitResult.length; i++){
document.write("
Element " + i + " = " + mySplitResult[i]);
}
javascript document.getelementbyid
If you want to quickly access the
value of an HTML input give it an id to make your life a lot easier. This
small script below will check to see if there is any text in the text field
"myText". The argument that getElementById requires is the id of the HTML element you wish to
utilize.
JavaScript Code:
function notEmpty(){
var myTextField = document.getElementById('myText');
if(myTextField.value != "")
alert("You entered: " + myTextField.value)
else
alert("Would you please enter some text?")
}
id='myText' />
changing text with innerhtml
Each HTML element has an innerHTML property that defines both the HTML
code and the text that occurs between that element's opening and closing tag.
By changing an element's innerHTML after some user interaction, you can
make much more interactive pages.
However, using innerHTML requires some preparation if you want
to be able to use it easily and reliably. First, you must give the element you
wish to change anid. With that id in place you will be able to use the getElementById function, which works on all browsers.
After you have that set up you
can now manipulate the text of an element. To start off, let's try changing the
text inside a bold tag.
JavaScript Code:
function changeText(){
document.getElementById('boldStuff').innerHTML = 'Fred Flinstone';
}
Welcome to the site dude
updating text based on user input
By adding a Text Input, we can take to updating our bold text
with whatever the user types into the text input. Note: We updated the function
a bit and set the id toboldStuff2.
JavaScript Code:
function changeText2(){
var userInput = document.getElementById('userInput').value;
document.getElementById('boldStuff2').innerHTML = userInput;
}
Welcome to the site dude
changing html with innerhtml
You can also insert HTML into
your elements in the exact same way. Let's say we didn't like the text that was
displayed in our paragraph and wanted to updated it with some color. The
following code will take the old black text and make it bright white. The only
thing we're doing different here is inserting the html element span to change the color.
JavaScript Code:
function changeText3(){
var oldHTML = document.getElementById('para').innerHTML;
var newHTML = "" + oldHTML + "";
document.getElementById('para').innerHTML = newHTML;
}
Welcome to the site dude
Comments
Post a Comment
Thank you for your Comment