Dev Notes – Javascript


Basics

  • 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
  1. What does it do – JavaScript gives HTML designers a programming tool – HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small “snippets” of code into their HTML pages.
  2. JavaScript can react to events – A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element.
  3. JavaScript can read and write HTML elements – A JavaScript can read and change the content of an HTML element
  4.  JavaScript can be used to validate data – A JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing.
  5. JavaScript can be used to detect the visitor’s browser – A JavaScript can be used to detect the visitor’s browser, and – depending on the browser – load another page specifically designed for that browser.
  6. JavaScript can be used to create cookies – A JavaScript can be used to store and retrieve information on the visitor’s computer.

Try to avoid using document.write() in real life JavaScript code. The entire HTML page will be overwritten if document.write() is used inside a function, or after the page is loaded. However, document.write() is an easy way to demonstrate JavaScript output. To manipulate HTML elements JavaScript uses the DOM method getElementById(). This Method accesses the element with the specified id.  JavaScripts can be put in the <body> and in the <head> sections of an HTML page.

Coding

<script type="text/javascript" src="xxx.js"></script>

 

<script type="text/javascript">
{
   document.write("<h1>This is a heading</h1>");
   document.write("<p>This is a paragraph.</p>");
   document.write("<p>This is another paragraph.</p>");
}
< /script>

 

var x;
var carname;
var x=5;
var carname="Volvo";

If you assign values to variables that have not yet been declared, the variables will automatically be declared as global variables. (if they don’t already exist).

Operator Description Example Result
+ Addition x=y+2 x=7 y=5
- Subtraction x=y-2 x=3 y=5
* Multiplication x=y*2 x=10 y=5
/ Division x=y/2 x=2.5 y=5
% Modulus (division remainder) x=y%2 x=1 y=5
++ Increment x=++y x=6 y=6
x=y++ x=5 y=6
-- Decrement x=--y x=4 y=4
x=y-- x=5 y=4
Operator Example Same As Result
= x=y x=5
+= x+=y x=x+y x=15
-= x-=y x=x-y x=5
*= x*=y x=x*y x=50
/= x/=y x=x/y x=2
%= x%=y x=x%y x=0
Operator Description Example
== is equal to x==8 is false
x==5 is true
=== is exactly equal to (value and type) x===5 is true
x==="5" is false
!= is not equal x!=8 is true
> is greater than x>8 is false
< is less than x<8 is true
>= is greater than or equal to x>=8 is false
<= is less than or equal to x<=8 is true
Operator Description Example
&& and (x < 10 && y > 1) is true
|| or (x==5 || y==5) is false
! not !(x==y) is true

if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if neither condition1 nor condition2 is true
}
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}

Popup Boxes
 alert("sometext");
 confirm("sometext"); OK or Cancel

Prompt Box
var name=prompt(“Please enter your name”,”Harry Potter”);
if (name!=null && name!=””)
{
document.write(“Hello ” + name + “! How are you today?”);
}
}

Functions
function functionname(var1,var2,…,varX)
{
some code
}
function product(a,b)
{
return a*b;
}

Loops

for (variable=startvalue;variable<=endvalue;variable=variable+increment)
{
code to be executed
}
while (variable<=endvalue)
{
code to be executed
}

do
{
code to be executed
}
while (variable<=endvalue);

 The break statement will break the loop and continue executing the code that follows after the loop (if any).
 The continue statement will break the current loop and continue with the next value.

For in
var person={fname:”John”,lname:”Doe”,age:25};

for (x in person)
{
document.write(person[x] + ” “);
}

Events
By using JavaScript, we have the ability to create dynamic web pages. Events are actions that can be detected by JavaScript.

Every element on a web page has certain events which can trigger a JavaScript. For example, we can use the onClick event of a button element to indicate that a function will run when a user clicks on the button. We define the events in the HTML tags.

Examples of events:
 A mouse click
 A web page or an image loading
 Mousing over a hot spot on the web page
 Selecting an input field in an HTML form
 Submitting an HTML form
 A keystroke

Note: Events are normally used in combination with functions, and the function will not be executed before the event occurs!

onLoad and onUnload

The onLoad and onUnload events are triggered when the user enters or leaves the page.

The onLoad event is often used to check the visitor’s browser type and browser version, and load the proper version of the web page based on the information.

Both the onLoad and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page. For example, you could have a popup asking for the user’s name upon his first arrival to your page. The name is then stored in a cookie. Next time the visitor arrives at your page, you could have another popup saying something like: “Welcome John Doe!”.

onFocus, onBlur and onChange
The onFocus, onBlur and onChange events are often used in combination with validation of form fields. Below is an example of how to use the onChange event. The checkEmail() function will be called whenever the user changes the content of the field:

<input type=”text” size=”30″ id=”email” onchange=”checkEmail()”>

onSubmit
The onSubmit event is used to validate ALL form fields before submitting it.

Below is an example of how to use the onSubmit event. The checkForm() function will be called when the user clicks the submit button in the form. If the field values are not accepted, the submit should be cancelled. The function checkForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled:

<form method=”post” action=”xxx.htm” onsubmit=”return checkForm()”>

onMouseOver

try
{
//Run some code here
}
catch(err)
{
//Handle errors here
}

throw exception

Insert Special Characters
Code Outputs
\’ single quote
\” double quote
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
\f form feed

 JavaScript is Case Sensitive
 JavaScript ignores extra spaces.
 You can break up a code line within a text string with a backslash. However you cannot break up document.write \
(“Hello World!”);

 

Objects
The String object is used to manipulate a stored piece of text.
var txt=”Hello world!”;
document.write(txt.length);
Outputs 12

var txt=”Hello world!”;
document.write(txt.toUpperCase());
Outputs HELLO WORLD

Date
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
var today = new Date()
var d1 = new Date(“October 13, 1975 11:13:00”)
var d2 = new Date(79,5,24)
var d3 = new Date(79,5,24,11,33,0)

var myDate=new Date();
myDate.setFullYear(2010,0,14);
var myDate=new Date();
myDate.setDate(myDate.getDate()+5); 5 days in future

Comparing Dates
var x=new Date();
x.setFullYear(2100,0,14);
var today = new Date();

if (x>today)
{
alert(“Today is before 14th January 2100”);
}
else
{
alert(“Today is after 14th January 2100″);
}

Arrays

<script type=”text/javascript”>
var i;
var mycars = new Array();
mycars[0] = “Saab”;
mycars[1] = “Volvo”;
mycars[2] = “BMW”;

for (i=0;i<mycars.length;i++)
{
document.write(mycars[i] + “<br />”);
}
</script>

Booleans
<script type=”text/javascript”>
var b1=new Boolean( 0);
var b2=new Boolean(1);
var b3=new Boolean(“”);
var b4=new Boolean(null);
var b5=new Boolean(NaN);
var b6=new Boolean(“false”);

document.write(“0 is boolean “+ b1 +”<br />”);
document.write(“1 is boolean “+ b2 +”<br />”);
document.write(“An empty string is boolean “+ b3 + “<br />”);
document.write(“null is boolean “+ b4+ “<br />”);
document.write(“NaN is boolean “+ b5 +”<br />”);
document.write(“The string ‘false’ is boolean “+ b6 +”<br />”);
</script>
Outputs
0 is boolean false
1 is boolean true
An empty string is boolean false
null is boolean false
NaN is boolean false
The string ‘false’ is boolean true

 

Math
Property Description
E
Returns Euler’s number (approx. 2.718)
LN2
Returns the natural logarithm of 2 (approx. 0.693)
LN10
Returns the natural logarithm of 10 (approx. 2.302)
LOG2E
Returns the base-2 logarithm of E (approx. 1.442)
LOG10E
Returns the base-10 logarithm of E (approx. 0.434)
PI
Returns PI (approx. 3.14159)
SQRT1_2
Returns the square root of 1/2 (approx. 0.707)
SQRT2
Returns the square root of 2 (approx. 1.414)
Math Object Methods
Method Description
abs(x)
Returns the absolute value of x
acos(x)
Returns the arccosine of x, in radians
asin(x)
Returns the arcsine of x, in radians
atan(x)
Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians
atan2(y,x)
Returns the arctangent of the quotient of its arguments
ceil(x)
Returns x, rounded upwards to the nearest integer
cos(x)
Returns the cosine of x (x is in radians)
exp(x)
Returns the value of Ex
floor(x)
Returns x, rounded downwards to the nearest integer
log(x)
Returns the natural logarithm (base E) of x
max(x,y,z,…,n)
Returns the number with the highest value
min(x,y,z,…,n)
Returns the number with the lowest value
pow(x,y)
Returns the value of x to the power of y
random()
Returns a random number between 0 and 1
round(x)
Rounds x to the nearest integer
sin(x)
Returns the sine of x (x is in radians)
sqrt(x)
Returns the square root of x
tan(x)
Returns the tangent of an angle

RegExp

 A regular expression is an object that describes a pattern of characters.
 When you search in a text, you can use a pattern to describe what you are searching for.
 A simple pattern can be one single character.

A more complicated pattern can consist of more characters, and can be used for parsing, format checking, substitution and more.

Regular expressions are used to perform powerful pattern-matching and “search-and-replace” functions on text.

Do a case-insensitive search for “w3schools” in a string:
var str=”Visit W3Schools”;
var patt1=/w3schools/i;
Do a global search for “is”:
var str=”Is this all there is?”;
var patt1=/is/g;

Do a global, case-insensitive search for “is”:
var str=”Is this all there is?”;
var patt1=/is/gi;

test()
The test() method searches a string for a specified value, and returns true or false, depending on the result.

The following example searches a string for the character “e”:
var patt1=new RegExp(“e”);
document.write(patt1.test(“The best things in life are free”));

Since there is an “e” in the string, the output of the code above will be:
true

exec()
The exec() method searches a string for a specified value, and returns the text of the found value. If no match is found, it returns null.
The following example searches a string for the character “e”:
var patt1=new RegExp(“e”);
document.write(patt1.exec(“The best things in life are free”));

Since there is an “e” in the string, the output of the code above will be:
E

Advanced

Browser Detection

The Navigator Object

<html>
<body>
<div id=”example”></div>

<script type=”text/javascript”>

txt = “<p>Browser CodeName: ” + navigator.appCodeName + “</p>”;
txt+= “<p>Browser Name: ” + navigator.appName + “</p>”;
txt+= “<p>Browser Version: ” + navigator.appVersion + “</p>”;
txt+= “<p>Cookies Enabled: ” + navigator.cookieEnabled + “</p>”;
txt+= “<p>Platform: ” + navigator.platform + “</p>”;
txt+= “<p>User-agent header: ” + navigator.userAgent + “</p>”;

document.getElementById(“example”).innerHTML=txt;

</script>

</body>
</html>

Cookies
Page with a browser, it will send the cookie too. With JavaScript, you can both create and retrieve cookie values.

Examples of cookies:
 Name cookie – The first time a visitor arrives to your web page, he or she must fill in her/his name. The name is then stored in a cookie. Next time the visitor arrives at your page, he or she could get a welcome message like “Welcome John Doe!” The name is retrieved from the stored cookie
 Password cookie – The first time a visitor arrives to your web page, he or she must fill in a password. The password is then stored in a cookie. Next time the visitor arrives at your page, the password is retrieved from the cookie
 Date cookie – The first time a visitor arrives to your web page, the current date is stored in a cookie. Next time the visitor arrives at your page, he or she could get a message like “Your last visit was on Tuesday August 11, 2005!” The date is retrieved from the stored cookie
<html>

<head>

<script type=”text/javascript”>
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(“;”);
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf(“=”));
y=ARRcookies[i].substr(ARRcookies[i].indexOf(“=”)+1);
x=x.replace(/^\s+|\s+$/g,””);
if (x==c_name)
{
return unescape(y);
}
}
}


Published by:  mike    October 27th, 2015    Ajax  

Leave a Reply

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