Enable Javascript - Internet Explorer
Enable Javascript - Internet Explorer
Enable Javascript - Internet Explorer
In Internet Explorer 6/7 (download Internet Explorer), you can check to see if JavaScript is
enabled by navigating to the custom security settings that are somewhat buried (don't worry;
we'll help you find it).
JavaScript Detection
These days, it's basically impossible to navigate the web without a JavaScript-enabled browser,
so checking whether or not a user has JavaScript enabled is not all that important. Chances are,
the only way it be disabled is if the company's IT staff has decided to disable JavaScript for some
reason. However, if you still want to be sure your users are JavaScript enabled, this script will
get it done.
The only sure fire way to separate users who don't have JavaScript from those who do is to use a
simple redirect script that will only work for those with JavaScript enabled. If a person's browser
does not have JavaScript enabled, the script will not run, and they will remain on the same page.
<html>
<body>
<script type="text/JavaScript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>
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.
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.
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:
<body>
<script type="text/JavaScript">
<!--
var linebreak = "<br />"
var my_var = "Hello World!"
document.write(my_var)
document.write(linebreak)
0
my_var = "I am learning JavaScript!"
document.write(my_var)
document.write(linebreak)
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).
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".
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
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
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.
//-->
</script>
</head>
<body>
Hover Me!
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 moves off the link
(onMouseout), we displayed a popup.
When a web page is loaded, the browser creates an object model of the page.
Using the DOM, JavaScript can access all the elements of an HTML document.
To do so, you have to find the elements first. There are a couple of ways to do this:
Often you will want to find HTML elements by using the element id. Use this DOM method:
var x=document.getElementById("id_name");
If the element is found, the method will return the element as an object (in x).
The easiest way to modify the content of an HTML element is by using the innerHTML
property.
<html>
<head>
<script>
function change(){
document.getElementById("p1").innerHTML="New text!";
}
</script>
</head>
<body>
</body>
</html>
Changing HTML Style
<script>
document.getElementById("p2").style.color="blue";
</script>
</body>
</html>
JavaScript Functions
A function is a block of code that executes only when you tell it to execute.
It can be when an event occurs, like when a user clicks a button, or from a call within your script,
or from a call within another function.
Functions can be placed both in the <head> and in the <body> section of a document, just make
sure that the function exists, when the call is made.
The { and the } defines the start and end of the function.
Note: Do not forget about the importance of capitals in JavaScript! The word function must be
written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a
function with the exact same capitals as in the function name.
JavaScript Function Example
Example
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
alert("Hello World!");
}
</script>
</head>
<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>
Try it yourself »
You will learn more about JavaScript events in the JS Events chapter.
When you call a function, you can pass along some values to it, these values are called
arguments or parameters.
You can send as many arguments as you like, separated by commas (,)
myFunction(argument1,argument2)
function myFunction(var1,var2)
{
some code
}
The variables and the arguments must be in the expected order. The first variable is given the
value of the first passed argument etc.
Example
<button onclick="myFunction('Harry Potter','Wizard')">Try
it</button>
<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>
The function above will alert "Welcome Harry Potter, the Wizard" when the button is clicked.
The function is flexible, you can call the function using different arguments, and different
welcome messages will be given:
Example
<!DOCTYPE html>
<html>
<body>
<p>Click one of the buttons to call a function with
arguments</p>
<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>
</body>
</html>
The example above will alert "Welcome Harry Potter, the Wizard" or "Welcome Bob, the
Builder" depending on which button is clicked.
Sometimes you want your function to return a value back to where the call was made.
When using the return statement, the function will stop executing, and return the specified value.
Syntax
function myFunction()
{
var x=5;
return x;
}
Note: It is not the entire JavaScript that will stop executing, only the function. JavaScript will
continue executing code, where the function-call was made from.
var myVar=myFunction();
The variable myVar holds the value 5, which is what the function "myFunction()" returns.
document.getElementById("demo").innerHTML=myFunction();
The innerHTML of the "demo" element will be 5, which is what the function "myFunction()"
returns.
You can make a returnvalue based on arguments passed into the function:
Example
document.getElementById("demo").innerHTML=myFunction(4,3);
12
The return statement is also used when you simply want to exit a function. The return value is
optional:
function myFunction(a,b)
{
if (a>b)
{
return;
}
x=a+b
}
The function above will exit the function if a>b, and will not calculate the sum of a and b.
JavaScript Objects
JavaScript has several built-in objects, like String, Date, Array, and more.
objectName.propertyName
This example uses the length property of the String object to find the length of a string:
12
objectName.methodName()
This example uses the toUpperCase() method of the String object, to convert a text to uppercase:
HELLO WORLD!
Creating JavaScript Objects
With JavaScript you can define and create your own objects.
This example creates a new instance of an object, and adds four properties to it:
Example
personObj=new Object();
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=50;
personObj.eyecolor="blue";
Example
personObj={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};
Math Object
var x=Math.PI;
var y=Math.sqrt(16);
Note: Math is not a constructor. All properties and methods of Math can be called by using Math
as an object without creating it.
Mathematical Constants
JavaScript provides eight mathematical constants that can be accessed from the Math object.
These are: E, PI, square root of 2, square root of 1/2, natural log of 2, natural log of 10, base-2
log of E, and base-10 log of E.
You may reference these constants from your JavaScript like this:
Math.E
Math.PI
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E
Mathematical Methods
In addition to the mathematical constants that can be accessed from the Math object there are
also several methods available.
The following example uses the round() method of the Math object to round a number to the
nearest integer:
document.write(Math.round(4.7));
The code above will result in the following output:
The following example uses the random() method of the Math object to return a random number
between 0 and 1:
document.write(Math.random());
The code above can result in the following output:
0.5339408550218532
The following example uses the floor() and random() methods of the Math object to return a
random number between 0 and 10:
document.write(Math.floor(Math.random()*11));
10
Browser Detection
Almost everything in this tutorial works on all JavaScript-enabled browsers. However, there are
some things that just don't work on certain browsers - especially on older browsers.
Sometimes it can be useful to detect the visitor's browser, and then serve the appropriate
information.
The Navigator object contains information about the visitor's browser name, version, and more.
The Navigator object contains all information about the visitor's browser:
<!DOCTYPE html>
<html>
<body>
<div id="example"></div>
<script>
document.getElementById("example").innerHTML=txt;
</script>
</body>
</html>
JavaScript can be used to validate data in HTML forms before sending off the content to a
server.
The function below checks if a field has been left empty. If the field is blank, an alert box alerts a
message, the function returns false, and the form will not be submitted:
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm()
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
return false;
</script>
</head>
<body>
</form>
</body>
</html>
E-mail Validation
The function below checks if the content has the general syntax of an email.
This means that the input data must contain an @ sign and at least one dot (.). Also, the @ must
not be the first character of the email address, and the last dot must be present after the @ sign,
and minimum 2 characters before the end:
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm()
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
return false;
</script>
</head>
<body>
</form>
</body>
</html>
Syntax
var patt=new RegExp(pattern,modifiers);
or more simply:
var patt=/pattern/modifiers;
Modifiers
Modifiers are used to perform case-insensitive and global searches:
Modifier Description
i Perform case-insensitive matching
Perform a global match (find all matches rather than stopping after the first
g
match)
m Perform multiline matching
<!DOCTYPE html>
<html>
<body>
<script>
document.write(str.match(patt1));
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
var patt1=/is/g;
document.write(str.match(patt1));
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
var patt1=/is/gi;
document.write(str.match(patt1));
</script>
</body>
</html>
Expression Description
[abc] Find any character between the brackets
[^abc] Find any character not between the brackets
[0-9] Find any digit from 0 to 9
[A-Z] Find any character from uppercase A to uppercase Z
[a-z] Find any character from lowercase a to lowercase z
[A-z] Find any character from uppercase A to lowercase z
[adgk] Find any character in the given set
[^adgk] Find any character outside the given set
(red|blue|green) Find any of the alternatives specified
<!DOCTYPE html>
<html>
<body>
<script>
var str="Is tHis all there is?";
var patt1=/[a-h]/g;
document.write(str.match(patt1));
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
var str="Is this all there is?";
var patt1=/[^a-h]/g;
document.write(str.match(patt1));
</script>
</body>
</html>
Metacharacters
Metacharacters are characters with a special meaning:
Metacharacter Description
. Find a single character, except newline or line terminator
\w Find a word character
\W Find a non-word character
\d Find a digit
\D Find a non-digit character
\s Find a whitespace character
\S Find a non-whitespace character
\b Find a match at the beginning/end of a word
\B Find a match not at the beginning/end of a word
\0 Find a NUL character
\n Find a new line character
\f Find a form feed character
\r Find a carriage return character
\t Find a tab character
\v Find a vertical tab character
\xxx Find the character specified by an octal number xxx
\xdd Find the character specified by a hexadecimal number dd
Find the Unicode character specified by a hexadecimal number
\uxxxx
xxxx
<!DOCTYPE html>
<html>
<body>
<script>
var str="Give is 100";
var patt1=/\w/g;
document.write(str.match(patt1));
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
var str="Give 100%!";
var patt1=/\W/g;
document.write(str.match(patt1));
</script>
</body>
</html>
Quantifiers
Quantifier Description
n+ Matches any string that contains at least one n
Matches any string that contains zero or more occurrences of
n*
n
n? Matches any string that contains zero or one occurrences of n
n{X} Matches any string that contains a sequence of X n's
n{X,Y} Matches any string that contains a sequence of X to Y n's
n{X,} Matches any string that contains a sequence of at least X n's
n$ Matches any string with n at the end of it
^n Matches any string with n at the beginning of it
?=n Matches any string that is followed by a specific string n
Matches any string that is not followed by a specific string n
?!n
<!DOCTYPE html>
<html>
<body>
<script>
var str="Hellooo World! Hello W3Schools!";
var patt1=/o+/g;
document.write(str.match(patt1));
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
var str="Hellooo World! Hello W3Schools!";
var patt1=/lo*/g;
document.write(str.match(patt1));
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
var str="1, 100 or 1000?";
var patt1= /10*/g;
document.write(str.match(patt1));
</script>
</body>
</html>
It's very easy to time events in JavaScript. The two key methods that are used are:
setInterval() - executes a function, over and over again, at specified time intervals
setTimeout() - executes a function, once, after waiting a specified number of milliseconds
Note: The setInterval() and setTimeout() are both methods of the HTML DOM Window object.
The setInterval() method will wait a specified number of milliseconds, and then execute a
specified function, and it will continue to execute the function, once at every given time-interval.
Syntax
setInterval("javascript function",milliseconds);
The second parameter indicates the length of the time-intervals between each execution.
Example
<!DOCTYPE html>
<html>
<body>
<p>Click the button to wait 3 seconds, then alert "Hello".</p>
<p>After clicking away the alert box, an new alert box will appear in 3 seconds. This goes on
forever...</p>
<script>
function myFunction()
setInterval(function(){alert("Hello")},3000);
</script>
</body>
</html>
The example show you how the setInterval() method works, but it is not very likely that you
want to alert a message every 3 seconds.
Below is an example that will display the current time. The setInterval() method is used to
execute the function once every 1 second, just like a digital watch.
Example
<html>
<body>
<script>
function myFunction()
setInterval(function(){myTimer()},1000);
function myTimer()
var t=d.toLocaleTimeString();
document.getElementById("demo").innerHTML=t;
</script>
<p id="demo"></p>
</body>
</html>
How to Stop the Execution?
The clearInterval() method is used to stop further executions of the function specified in the
setInterval() method.
Syntax
clearInterval(intervalVariable)
To be able to use the clearInterval() method, you must use a global variable when creating the
interval method:
myVar=setInterval("javascript function",milliseconds);
Then you will be able to stop the execution by calling the clearInterval() method.
Example
Same example as above, but we have added a "Stop the timer" button:
<!DOCTYPE html>
<html>
<body>
<p>Click the first button to display the current time, and the second button to stop the time.</p>
<script>
var myVar;
function myFunction()
myVar=setInterval(function(){myTimer()},1000);
}
function myTimer()
var t=d.toLocaleTimeString();
document.getElementById("demo").innerHTML=t;
function myStopFunction()
clearInterval(myVar);
</script>
<p id="demo"></p>
</body>
</html>
The setTimeout() method will wait the specified number of milliseconds, and then execute the
specified function.
The second parameter indicates how many milliseconds, from now, you want to execute the first
parameter.
Example
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction()
setTimeout(function(){alert("Hello")},3000);
</script>
</body>
</html>
The clearTimeout() method is used to stop the execution of the function specified in the
setTimeout() method.
Syntax
clearTimeout(timeoutVariable)
To be able to use the clearTimeout() method, you must use a global variable when creating the
timeout method:
myVar=setTimeout("javascript function",milliseconds);
Then, if the function has not allready being executed, you will be able to stop the execution by
calling the clearTimeout() method.
Example
Same example as above, but we have added a "Stop the alert" button:
<!DOCTYPE html>
<html>
<body>
<p>Click the second button to prevent the first function to execute. (You must click it before the 3
seconds are up.)</p>
<script>
var myVar;
function myFunction()
myVar=setTimeout(function(){alert("Hello")},3000);
function myStopFunction()
clearTimeout(myVar);
}
</script>
</body>
</html>