আগামী ৩০ অক্টোবর -২০১৭ তারিখ থেকে শুরু হচ্ছে পাঁচ মাস ব্যাপী Professional Web Design and Development with HTML,CSS,Bootstrap,PHP,MySQl, AJAX and JQUERY কোর্সের ৮৬ তম ব্যাচ। আগ্রহীদেরকে অতিসত্বর মাসুদ আলম স্যার এর সাথে যোগাযোগ করতে অনুরোধ করা যাচ্ছে। স্যার এর মোবাইল: 01722817591, Email : [email protected] কোর্সের সিলেবাস এর জন্য এখানে ক্লিক করুন ।

JAVASCRIPT Beginner Tutorial

[printfriendly]

JAVASCRIPT Beginner Tutorial

What is JavaScript?

  • JavaScript was designed to add interactivity to HTML pages
  • JavaScript is a scripting language
  • A scripting language is a lightweight programming language
  • JavaScript is usually embedded directly into HTML pages
  • JavaScript is an interpreted language (means that scripts execute without preliminary compilation)
  • Everyone can use JavaScript without purchasing a license

JavaScript – Syntax

 

<html>
<body>
<script type=”text/javascript”>

</script>
</body>
</html>

JavaScript Comments

  1. Singl Line Comments
  2. Multiline comments

Single Line Comments Examples:

<html>
<head>
<title>A Simple Page</title>
<script language="javascript">
<!--
// The first alert is below
alert("An alert triggered by JavaScript!");
// Here is the second alert
alert("A second message appears!");
//  -->
</script>
</head>
<body>

</body>
</html>

Multiline comments Examples:

<html>
<head>
<title>A Simple Page</title>
<script language="javascript">
<!--
/*
Below two alert() methods are used to
fire up two message boxes - note how the
second one fires after the OK button on the
first has been clicked
*/
alert("An alert triggered by JavaScript!");
alert("A second message appears!");
//  -->
</script>
</head>
<body>

</body>
</html>

JavaScript Keywords

Keywords are reserved and cannot be used as variable or function names.

Here is the complete list of JavaScript keywords:

break        else          New      var
case         finally       return   void
catch        for           switch   while
continue     function      This     with
default      if            throw
delete       in            try
do           instanceof    typeof

 

 

JavaScript Reserved Words

 

The reserved words are words that are reserved for future use as keywords.

The reserved words cannot be used as variable or function names.

The complete list of reserved words is as follows:

abstract      enum        int        short
boolean       Export      interface  static
byte          extends     long       super
char          final       native     synchronized
class         float       package    throws
const         goto        private    transient
debugger      implements  protected  volatile
double        Import      public

JavaScript Semicolon

JavaScript executes your code accordingly even if you forget a semicolon at the end of the line.

You must use a semicolon to separate the two pieces of code when putting two independent pieces of code on one line.

<html>
<body>
<SCRIPT LANGUAGE="JavaScript">

<!--
// Declare 2 numeric variables on the same line
var varA = 5; var varB = 0.06;

document.write(varA*varB);
-->

</SCRIPT>
</body>
</html>

JavaScript  Variable

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:

<html>

<body>
<script type="text/JavaScript">
<!--
var linebreak = "<br />"
var my_var = "Hello World!"

document.write(my_var)
document.write(linebreak)

my_var = "I am learning JavaScript!"
document.write(my_var)
document.write(linebreak)

my_var = "Script is Finishing up..."
document.write(my_var)
//-->
</script>
</body>

</html>

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 for 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, 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. This is an easy way to organize the variables in your code and see when they came into existence. 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 Variable Scope

A variable can be either global or local in JavaScript.

All variables are global unless they are declared in a function.

Variables declared in a function are local to that function.

It is possible for two variables with the same name to exist if one is global and the other is local.

When accessing the variable within the function, you are accessing the local variable.

If the variable is accessed outside the function, the global variable is used.

Always use the var keyword to declare local variables in functions.

Without var, JavaScript will create a global variable.

Variable names are case sensitive (y and Y are two different variables)

Variable names must begin with a letter or the underscore character

Variables in JavaScript are defined by using the var operator (short for variable), followed by the variable name, such as:

var test = "hi";

In this example, the variable test is declared and given an initialization value of “hi” (a string).

You can also define two or more variables using the same var statement:

var test = "hi", test2 = "hola";

Variables using the same var statement don’t have to be of the same type:

var test = "hi", age = 25;

variables in JavaScript do not require initialization:

var test;

A variable can be initialized with a string value, and later on be set to a number value.

var test = "hi";
alert(test);
test = 55;
alert(test);

Code blocks indicates a series of statements that should be executed in sequence.

Code blocks are enclosed between an opening brace ({) and a closing brace (}).

if (test1 == "red") {
   test1 = "blue";
   alert(test1);
}

Example of JavaScript Local and Global Variables:

<SCRIPT LANGUAGE="JavaScript">
<!--
function function_1 ()
{
var x = 5;
document . write ("<br>Inside function_1, x=" + x);
function_2 ();
document . write ("<br>Inside function_1, x=" + x);
}
function function_2 () {
document . write ("<br>Inside function_2, x=" + x);
}
x = 1;
document . write ("<br>Outside, x=" + x);
function_1 ();
document . write ("<br>Outside, x=" + x)
-->
</SCRIPT>

JavaScript Functions

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 repetitive 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 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:

<html>
<head>
<script type="text/javascript">
<!--
function popup() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="popup()" value="popup">
</body>
</html>

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

JavaScript Operators

Operators

The most common operators are mathematical operators; +, -, /, * (add, subtract, divide, multiply) for example. Operators can be split into two groups, comparison operators and assignment or ‘action’ operators. Comparison operators test to see if two variables relate to each other in the specified way, for example, one variable is a higher number than the other. Other operators perform an action on a variable, such as increasing it by one.

The following table gives those that are most commonly used. The JavaScript 1.3 operators such as the identity operator === are supported by all current browsers, but are not used as often as the others. Old browsers that do not understand them will just produce errors.

JavaScript operators

Operator

Uses

+

adds two numbers or appends two strings – if more than one type of variable is appended, including a string appended to a number or vice-versa, the result will be a string

-

subtracts the second number from the first

/

divides the first number by the second

*

multiplies two numbers

%

divide the first number by the second and return the remainder

=

assigns the value on the right to the object on the left

+=

the object on the left = the object on the left + the value on the right – this also works when appending strings

-=

the object on the left = the object on the left – the value on the right

> 

number on the left must be greater than the number on the right – this also works with strings and values

< 

number on the left must be less than the number on the right – this also works with strings and values

>=

number on the left must be greater than or equal to the number on the right – this also works with strings and values

<=

number on the left must be less than or equal to the number on the right – this also works with strings and values

++

increment the number

--

decrement the number

==

the numbers or objects or values must be equal

!=

the numbers or objects or values must not be equal

<< 

bitwise leftshift

>> 

bitwise rightshift

&

bitwise AND

|

bitwise OR

^

bitwise XOR

~

bitwise NOT

!

logical NOT (the statement must not be true)

&&

logical AND (both statements must be true)

||

logical OR (either statement must be true)

in

object or array on the right must have the property or cell on the left

===

the numbers or objects or values must be equal, and must be the same variable type

!==

the numbers or objects or values must not be equal, or must not be the same variable type

Example of Addition Assignment:

<html>
<script language="JavaScript">
<!--
num = 42;
str = new String("42");
num += 8;
str += 8;
document.write("num = ",num,"<br>str = ",str);
-->
</script>
</html>

OR

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--
var A = "JavaScript ", B = "by Example!";
C = A + B;
alert(C);
//  -->
</script>
</head>
<body>

</body>
</html>

JavaScript Conditionals Statement

 

  1. 1.      if……… else statement

 

The format of a simple if statement looks like the following:

if (expression)
      statement;

If the ‘expression’ in parentheses evaluates to true, the statement is executed; otherwise, the statement is skipped.

If two or more lines of code are to be executed, curly braces {} must be used to designate what code belongs in the if statement.

The keyword else extends the functionality of the basic if statement by providing other alternatives.

The format of an if…else combination looks like the following:

if (expression)
      statement1;
   else
      statement2;

if the expression evaluates to true, statement1 is executed, otherwise, statement2 is executed.

<html>
<SCRIPT LANGUAGE='JavaScript'>
<!--
var varA = 2;
var varB = 5;

if (varA == 0)
document.write("varA == 0");
else {
if ((varA * 2) >= varB)
document.write("(varA * 2) >= varB");
else
document.write("(varA * 2) < varB");
document.write(varB);
}
//-->
</SCRIPT>
</html>

[/html</pre>
<strong>Another Example:</strong>



<html>
<body>
<script lanuguage="JavaScript">
<!--
var temp = 1;

if(temp == true){
document.write("Statement is true");
} else{
document.write("Statement is false");
}

-->
</script>
</body>
</html>

 1.                    for Loops….

 

The for loop is a structure that loops for a preset number of times.

The for loop is made up of two parts: condition and statement.

The condition structure determines how many times the loop repeats.

The statement is what is executed every time the loop occurs.

The condition structure is contained within parentheses and is made up of three parts.

Each part is separated by a semicolon (;).

The first part of the condition structure initializes a variable to a starting value.

In most cases, the variable is declared within this section as well as initialized.

The second part is the conditional statement.

The third and final part determines how the variable should be changed each time the loop is iterated.

The format of the for loop looks like the following:

for (initialize; condition; adjust)  {
      statement;
    }
<html>
<SCRIPT LANGUAGE='JavaScript'>
<!--
document.write("<H2>Multiplication table for 4</H2>");

for (var aNum = 0; aNum <= 10; aNum++)
{
document.write("4 X ",aNum," = ",4*aNum,"<BR>");
}
//-->
</SCRIPT>
</html>

Or

<html>
<SCRIPT LANGUAGE='JavaScript'>
<!--
document.write("<H2>Multiplication table for 4</H2>");

for (var aNum = 0; aNum <= 10;)
{
document.write("4 X ",aNum," = ",4*aNum,"<BR>");
aNum++
}
//-->
</SCRIPT>
</html>

Another for loop example

<HTML>
<HEAD>
<TITLE>
Using the JavaScript for Loop
</TITLE>
</HEAD>

<BODY>
<H1>Using the JavaScript for Loop</H1>
<SCRIPT LANGUAGE="JavaScript">
<!--
var i, total
total = 0
for (i = 1; i < 5; i++) {
total += i
document.write("Loop iteration " + i + " (Cumulative total = "  + total + ")<BR>")
}
// -->
</SCRIPT>
</BODY>
</HTML>

Reversed for loop example

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--
for (x = 10; x >= 0; x = x - 2)
{
document.write(x+" " );
}
//  -->
</script>
</head>
<body>

</body>
</html>

JavaScript Switch

 

JavaScript offers the switch statement as an alternative to using the if…else structure.

The switch statement is useful when testing all the possible results of an expression.

The format of a switch structure looks like the following:

switch (expression)
    {
      case label1:
        statement1;
        break;
      case label2:
        statement2;
        break;
      default:
        statement3;
    }

The switch statement evaluates an expression placed between parentheses.

The result is compared to labels associated with case structures that follow the switch statement.

If the result is equal to a label, the statement(s) in the corresponding case structure are executed.

A default is used at the end of a switch structure to catch results that do not match any of the case labels.

A colon always follows a label.

Curly brackets {} are used to hold all the case structures together, but they are not used within a case structure.

The keyword break is used to break out of the entire switch statement once a match is found, thus preventing the default structure from being executed accidentally.

Example 1

<html>
<SCRIPT LANGUAGE='JavaScript'>
<!--
var color = "green";
switch (color)
{
case "red":
document.write("The car is red.");
break;
case "blue":
document.write("The car is blue.");
break;
case "green":
document.write("The car is green.");
break;
default:
document.write("The car is purple.");
}
//-->
</SCRIPT>
</html>

JavaScript While Loop

 

The while loop can be summarized as while the expression evaluates to true, execute the statements in the loop.

Once the last statement in the loop is executed, go back to the top of the loop and evaluate the expression again.

When the expression evaluates to false, the next line of code following the while loop structure is executed.

Because the expression is evaluated before the loop, it is possible the loop will never be executed.

The format of the while loop looks like the following:

while (expression)
    {
      statement;
    }

Example 1

<html>
<head>
</head>
<body>

<SCRIPT LANGUAGE='JavaScript'>
<!--
var counter = 1;
document.write("While loop is Starting<br>");
while (counter <= 5)
{
document.write("Counter Now",counter,"<BR>");
counter++;   //Next car
}
document.write("While loop is finished!");
//-->
</SCRIPT>
</body>
</html>

JavaScript Do While Loop

 

do…while loop always executes the loop once before evaluating the expression for the first time.

This difference is seen in the following format:

do
    {
       statement;
    }
    while (expression);

Once the loop has executed for the first time, the expression is evaluated.

If true, the loop is executed again.

When the expression evaluates to false, the next line of code following the while structure is executed.

A semicolon (;) must be placed after the rightmost parenthesis.

Example 1:

<html>
<body>
<SCRIPT LANGUAGE='JavaScript'>
<!--
var counter = 1;
do
{
document.write(counter + "<BR>");
counter++;
}
while (counter < 5);
//-->
</SCRIPT>
</body>
</html>

Example 2:

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--
var x = 1
do
{
++x;
document.write(x+" ");
}
while (x < 10);

//  -->
</script>
</head>
<body>

</body>
</html>

JavaScript Continue

 

The continue statement forces the execution of the code to continue at the beginning of the loop.

When a label is used, JavaScript immediately jumps to the beginning of the loop designated by a label and begins executing code.

Example 1:

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--
var x = 0;
while (x < 10)
{
x++;
document.write(x);
continue;
document.write("You never see this!");
}
//  -->
</script>
</head>
<body>

</body>
</html>

Example 2:

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--
var x = 0;
while (x < 10) {
x++;
if (x == 5) {
continue;
}
document.write(x);
}

//  -->
</script>
</head>
<body>

</body>
</html>

JavaScript Array

 

Array Constructors:

 

var variable = new Array()
var variable = new Array(int)
var variable = new Array(arg1, ..., argN)

These constructors create a new array and initialize the Array object based on the arguments passed in the parameter list.

The constructor that has no arguments sets the length property to 0.

int– An array is created and its length property is set to the value int.

arg1,…argN–An array is created and the array is populated with the arguments. The array length property is set to the number of arguments in the parameter list.

The newly created array is returned from the constructor

Use Array’s Constructor

 

Arrays stores multiple data based on a numbered position into one storage structure.

The index starts at 0 and goes up.

JavaScript supports having arrays within arrays, called multidimensional arrays.

One-Dimensional array

To create an instance of an array, you use the new operator along with the Array object.

There are four ways to declare an array.

First, an empty array can be created by leaving the constructor parameters empty:

var x = new Array();

The second way to create an array is to fill in the constructor parameters with the array elements.

An array can contain elements of various types:

var x = new Array("A","BB","CCC",1,5,8);

The third way to create an array is to fill in the constructor parameter with the size of the array.

This initializes the array to hold the number of elements specified, but does not specify the actual elements.

var x = new Array(6);

The fourth way to create an array is to use the array square brackets to fill in the array elements directly.

var x = ["A","BB","CCC",1,5,8];

 

 Creating an Array and Accessing Its Elements:

<html>
<body>
<h2>Creating and Accessing Arrays</h2>
<script language="JavaScript">
<!--
numArray = new Array(4,6,3);

document.write("[0]=",numArray[0],"<br>");
document.write("[1]=",numArray[1],"<br>");
document.write("[2]=",numArray[2]);
//End Hide-->
</script>
</body>
</html>

Create an array using the Object() constructor:

<html>
<body>
<SCRIPT LANGUAGE="JavaScript">
<!--
var myArray = Object();
myArray.length=3;   //array position zero
myArray[1]="A";
myArray[2]="B";
myArray[3]="C";

document.write("The myArray holds:  ");

for(x=1; x<=myArray.length; x++) {
document.write(myArray[x],"  ");
}
-->
</SCRIPT>
</body>
</html>

Array declaration with element count:

<html>
<head>
<title>A Simple Page</title>
<script language="javascript">
<!--
var days_of_week = new Array(7);
days_of_week[0] = "Sunday";
days_of_week[1] = "Monday";
days_of_week[2] = "Tuesday";
days_of_week[3] = "Wednesday";
days_of_week[4] = "Thursday";
days_of_week[5] = "Friday";
days_of_week[6] = "Saturday";
var x = 2;
alert(days_of_week[x]);
//  -->
</script>
</head>
<body>

</body>
</html>

Initialize a string array during declaration and check the array size:

 

<html>
<head>
<title>A Simple Page</title>
<script language="javascript">
<!--
var days_of_week = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
alert(days_of_week.length);
//  -->
</script>
</head>
<body>

</body>
</html>

Define two arrays and use for statement to output their values:

<html>
<head>
<title>Define two arrays and use for statement to ouput their values</title>

</head>
<body>

<h1>Define two arrays and use for statement to ouput their values</h1>

<table border="1" width="200">

<script language="javascript" type="text/javascript">
<!--

var myArray    = new Array();
myArray[0] = "A";
myArray[1] = "B";
myArray[2] = "C";
myArray[3] = "D";
myArray[4] = "E";

var myArray2    = new Array();
myArray2[0] = "1";
myArray2[1] = "2";
myArray2[2] = "3";
myArray2[3] = "4";
myArray2[4] = "5";

for (var i=0; i<myArray.length; i++) {
document.write("<tr><td>" + myArray[i] + "</td>");
document.write("<td>" + myArray2[i] + "</td></tr>");
}

//-->
</script>

</table>

</body>
</html>

Store strings in array:

<html>
<head>
<title>Store strings in array</title>

</head>
<body>
<P>

<script language="javascript" type="text/javascript">
<!--

var myArray = new Array();
myArray[0] = "AAA";
myArray[1] = "BBB";
myArray[2] = "CCC";
for (var i=0; i<myArray.length; i++) {
document.write("Element " +i+ " contains: " +myArray[i]+ "<br />");
}

//-->
</script>

</p>

</body>
</html>

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’s sort method.

<script type="text/javascript">
<!--
var myArray2= new Array();

myArray2[0] = "Football";
myArray2[1] = "Baseball";
myArray2[2] = "Cricket";

document.write(myArray2.sort());

//-->
</script>

Output:

 Baseball,Cricket,Football

Get Array length:

<html>
<head>
<title>Get Array length</title>

<script language="javascript" type="text/javascript">
<!--

var x = new Array(2,3,4);

alert(x.length);

//-->
</script>

</head>
<body>

</body>
</html>

JavaScript Alert

 

JavaScript Alert Example 1:

 

</strong>

<HTML>
<HEAD>
<TITLE>Using alert Boxes</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
function displayer()
{
alert("Hello from JavaScript!")
}
//-->
</SCRIPT>
</HEAD>

<BODY>
<H1>Using alert Boxes</H1>
<FORM>
<INPUT TYPE="BUTTON" ONCLICK="displayer()" VALUE="Click Me!">
</FORM>
</BODY>
<HTML>

JavaScript Prompt

<h2 align="center"><strong>JavaScript Confirm function</strong></h2>
&nbsp;



<html>
<head>
<title>A Simple Page</title>
<script language="javascript">
<!--
confirm("Which one will you choose?")
//  -->
</script>
</head>
<body>

</body>
</html>

JavaScript Confirm function

<html>
<head>
<title>A Simple Page</title>
<script language="javascript">
<!--
confirm("Which one will you choose?")
//  -->
</script>
</head>
<body>

</body>
</html>

Confirm dialog returns boolean value:

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--
var response = confirm("Do you want to proceed with this book?  Click OK to proceed otherwise click Cancel.");
alert(response)
//  -->
</script>
</head>
<body>

</body>
</html>

Use Confirm dialog in if statement:

<html>
<head>
<script Language="Javascript" type = "text/javascript">
<!--
var newurl

function CheckRequest(newurl)
{
if (confirm("Do you want to visit " + newurl + " site.")) {
return true
} else {
return false
}
}

//-->
</script>
<title>Capturing Links</title>
</head>
<P><A href="http://www.google.com" onClick = "return CheckRequest('java2s')">Java</A></P>
<P><A href="http://www.netscape.com" onClick = "return CheckRequest('Netscape')">Netscape</A></P>
</body>
</html>

Use confirms method in if statement:

<html>
<head>
<script language="JavaScript" type = "text/javascript">
<!--
var username = prompt("Type your name:", "");

if (confirm("Your name is: " + username + ". Is that correct?") == true )
{
alert("Hello " + username);
}
else
{
alert("Hi");
}
//-->
</script>
</head>
</html>

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.

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>

<body>
<form>
<input type="button" value="Print This Page" onClick="window.print()" />
</form>

</body>
</html>


Display:

If you click this button you should be prompted with whatever application your computer uses to handle its print functionality.

JavaScript Redirect

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

When your webpage is moved, you’d probably want to notify your visitors of the change. One good way is to place a “redirect page” at the old location which, after a timed delay, will forward visitors to the new location of your webpage. You can do just this with a JavaScript redirection.

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:

<pre><script type="text/javascript">
<!--
window.location = "http://www.google.com/"
//-->
</script></pre>

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>
<head>
<script type="text/javascript">
<!--
function delayer(){
window.location = "../javascriptredirect.php"
}
//-->
</script>
</head>
<body onLoad="setTimeout('delayer()', 5000)">
<h2>Prepare to be redirected!</h2>
<p>This page is a time delay redirect, please update your bookmarks to our new
location!</p>

</body>
</html>

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 Popups

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 (i.e. a hyperlink).

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>
<head>
<script type="text/javascript">
<!--
function myPopup() {
window.open( "http://www.google.com/" )
}
//-->
</script>
</head>
<body>
<form>
<input type="button" onClick="myPopup()" value="POP!">
</form>
<p onClick="myPopup()">CLICK ME TOO!</p>
</body>
</html>

CLICK ME TOO!

This works with pretty much any tag that can be clicked on, so please go ahead and 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:

  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!

Now that we have the tools, let’s make a sophisticated JavaScript popup window that we can be proud of!

HTML & JavaScript Code:

</p>
<p onclick="myPopup()"><head>
<script type="text/javascript">
<!--
function myPopup2() {
window.open( "http://www.google.com/", "myWindow",
"status = 1, height = 300, width = 300, resizable = 0" )
}
//-->
</script>
</head>
<body>
<form>
<input type="button" onClick="myPopup2()" value="POP2!">
</form>
<p onClick="myPopup2()">CLICK ME TOO!</p>
</body>

CLICK ME TOO!

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 with 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 times from the one created on 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.

<h4>It is now
<script type="text/javascript">
<!--
var currentTime = new Date()
//-->
</script>
</h4>

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, 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.

<h4>It is now
<script type="text/javascript">
<!--
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(month + "/" + day + "/" + year)
//-->
</script>
</h4>

Output

 

It is now 1/31/2012 !

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).

<h4>It is now
<script type="text/javascript">
<!--
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10){
minutes = "0" + minutes
}
document.write(hours + ":" + minutes + " ")
if(hours > 11){
document.write("PM")
} else {
document.write("AM")
}
//-->
</script>
</h4>

Output:

<h4>It is now<span>  </span>
<script type="text/javascript">
<!--
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10){
minutes = "0" + minutes
}
document.write(hours + ":" + minutes + " ")
if(hours > 11){
document.write("PM")
} else {
document.write("AM")
}
//-->
</script>
</h4>

Output:

It is now 12:51 PM

Above, we check to see if either the hours or minutes variable 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, our clock would output “1:1 AM”, which doesn’t look very nice at all!

Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I graduated in 2009 with a bachelor's degree in Engineering from State University Of Bangladesh, I'm also a Certified Engineer on ZEND PHP 5.3, I served my first five years a number of leadership positions at Winux Soft Ltd, SSL Wireless Ltd, CIDA and MAX Group where I worked on ERP software and web development., but now i'm a co-founder and Chief Executive Officer and Managing Director of TechBeeo Software Consultancy Services Ltd. I'm also a Course Instructor of ZCPE PHP 7 Certification and professional web development course at w3programmers Training Institute - a leading Training Institute in the country.
4 comments on “JAVASCRIPT Beginner Tutorial

Leave a Reply

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