Saturday, February 25, 2012

JavaScript

index  



<html><body>
<script type="text/javascript">
document.write("<p>" + Date() + "</p>");
</script>
</body></html> 
-----------------------
<p id = "demo">This is a paragraph </p>
<script type="text/javascript">
document.getElementById("demo").innerHTML=Date();
// the browser will replace the content of the HTML element with id = "demo", with the current date
//JavaScript is placed at the bottom of the page to make sure it is not executed before the <p> element is created
</script>
--------------------------
<head> <script type="text/javascript">
function displayDate()
{ document.getElementById("demo").innerHTML=Date(); }
</script> </head>
<body>
<button type = "button" onclick = "displayDate()">
Display Date</button>
<p id = "demo"></p>
</body>
It is a common practice to put all functions in the head section, or at the bottom of the page. This way they are all in one place and do not interfere with page content.
--------------------------
JavaScript can be placed in external JS file.
a.html
<html><head>
<script type ="text/javascript" src="javascript.js"></script>
</head><body>
<button type = "button" onclick = "displayDate()">Display Date </button>
<p  id = "demo"></p>
</body></html>
javascript.js
function displayDate()
{ document.getElementById("demo").innerHTML = Date(); }
-----------------------------
<html><head></head><body>
bbbbbbbbbbbbbb
<script type="text/javascript">
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
</script> 
aaaaaaaaaaaa
</body></html>
-----------------------
<script type="text/javascript">
/*
multiline
comments
*/
// one-line comment
</script> 
-----------------------
var x = 5;
var carname = "Volvo";
-----------------------
A variable declared with var inside a function is LOCAL (valid only inside the function) 
A variable declared without var is GLOBAL (valid in the entire web page) 
function displayDate() { 
var x;  // LOCAL
y;     //GLOBAL
x = 1;
y = "aaa";
}
-----------------------
x += y // same as x = x + y;
txt1 = "What a very";
txt2 = "nice day";
txt3 = txt1 + txt2;
-----------------------
If you add a number and a string, the result will be a string!
x = 5 + "5";
document.write(x); // 55
x = "6" + 6;
document.write(x); // 66
-----------------------
age = "17"; // string is interpreted as number!!
if (age < 18)   document.write("Too young");
else  document.write("adult");
----------------------------
&& and      || or      ! not 
----------------------------
greeting = (visitor=="PRES") ? "Dear President " : "Dear ";
if (visitor == "PRES")
 greeting = "Dear President ";
else
 greeting = "Dear ";
----------------------------
var d = new Date();
var time = d.getHours();
if (time < 12) 
 document.write("<b>Good morning</b>");
else if (time < 18)
 document.write("<b>Good afternoon</b>");
else
 document.write("<b>Good evening</b>");
----------------------------
var d = new Date();
var theDay = d.getDay(); //returns the day of the week (from 0 to 6)
switch (theDay) {
case 5:
  document.write("Friday");  break;
case 6:
  document.write("Saturday"); break;
case 0:
  document.write("Sunday"); break;
default:
  document.write("Outro dia");
}
----------------------------
POPUP
alert("sometext"); //OK 
var r = confirm("sometext"); //OK cancel
if (r == true) OK else cancel
var name = prompt("enter your name","Harry Potter");
if (name != null && name != "")
-------------------------
onblur an element loses focus
onchange an element change
onclick mouse click
ondblclick mouse double-click
onerror An error occurs when loading
onfocus an element gets focus
onmousedown mouse button is pressed
onmousemove mouse pointer moves
onmouseout mouse pointer moves out of an element
onmouseover mouse pointer moves over an element
onmouseup mouse button is released
onkeydown a key is pressed
onkeypress a key is pressed and released
onkeyup a key is released
onselect an element is selected 
onload A page or image is finished loading 
onresize A window or frame is resized 
onselect Text is selected 
onunload The user exits the page 
-------------------------
<html><head><script type="text/javascript">
function product(a,b) { return a * b; }
</script></head><body><script type="text/javascript">
document.write(product(4,4));
</script></body></html>
-------------------------
for (i = 0; i <= 5; i++) 
{  document.write("The number is " + i + "<br />"); }
-------------------------
var i = 0;
while (i <= 5) {
  document.write("The number is " + i + "<br />");
  i++;
}
-------------------------
var i = 0;
do {
  document.write("The number is " + i + "<br />");
  i++;
} while (i <= 5);
-------------------------
for (i = 0; i <= 10; i++) {
  if (i == 3) break;
  document.write("The number is " + i + "<br />");
}
-------------------------
var person = { 
firstName : "John",
Surname : "Doe",
age : 25   }; 
for (x in person) document.write(person[x] + " ");
-------------------------
<html><head><script type="text/javascript">
function isKeyPressed(event) {
if (event.altKey)  alert("ALT key");
else            alert("No ALT key");
}
</script></head>
<body onmousedown = "isKeyPressed(event)" >
<p> Click somewhere in the document. An alert box will tell you if you pressed the ALT key or not.
</p>
</body></html> 
-------------------------
<html><head><script type="text/javascript">
var txt = "";
function message()
{
try {  adddlert("Welcome guest!");  } 
catch( err ) {
txt = "There was an error on this page.\n\n";
txt += "Error description: " + err.description + "\n\n";
txt += "Click OK to continue.\n\n";
alert(txt);  }
}
</script></head>
<body>
<input type = "button" value = "View message" onclick = "message()" />
</body></html>
-----------------------------
var x = prompt("Enter a number between 0 and 10:","");
try { 
  if(x > 10)        throw "Err1";
  else if(x < 0)     throw "Err2";
  else if(isNaN(x))  throw "Err3";
} catch( er ) {
  if(er == "Err1") alert("Error! The value is too high");
  if(er == "Err2") alert("Error! The value is too low");
  if(er == "Err3") alert("Error! The value is not a number");
}
-----------------------------
\' single quote 
\" double quote 
\\ backslash 
\n new line 
\r carriage return 
\t tab 
\b backspace 
\f form feed 
-----------------------------
var txt = "Hello World!";
document.write(txt.length);
document.write(txt.toUpperCase());
-----------------------------
http://www.w3schools.com/jsref/jsref_obj_string.asp
http://www.w3schools.com/jsref/jsref_obj_date.asp
http://www.w3schools.com/jsref/jsref_obj_math.asp
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
-----------------------------
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");
-----------------------------
ARRAY
var myCars = new Array(); 
// regular array (add an optional integerargument to control array's size)
myCars[0]="Saab"; 
myCars[1]="Volvo";
myCars[2]="BMW";
var myCars = new Array("Saab","Volvo","BMW");
var myCars = ["Saab","Volvo","BMW"]; 
-----------------------------
var myBoolean = new Boolean();
-----------------------------
var x = Math.PI;
var y = Math.sqrt(16);
document.write(Math.round(4.7));
document.write(Math.random());
-----------------------------
REGULAR EXPRESSIONS
new RegExp("regexp","i")
/regexp/i 
<html><head></head><body><script type="text/javascript">
var patt1 = new RegExp("e");
document.write(patt1.test("The best things in life are free")); //true
document.write(patt1.exec("The best things in life are free"));//e
</script></body></html>
-----------------------------
<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;
-----------------------------
<html><head><script type="text/javascript">
function validateForm()
{
var x = document.forms["myForm"]["fname"].value
if (x == null || x == "")
{
  alert("First name must be filled out");
  return false;
}
}
</script></head><body>
<form name="myForm" action="someURL" onsubmit = "return validateForm()" 
method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body></html>
-----------------------------
<html><head><script type="text/javascript">
function validateForm() {
var x = document.forms["myForm"]["email"].value
var atpos = x.indexOf("@");
var dotpos = x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length){
  alert("Not a valid e-mail address");
  return false; } }
</script></head><body>
<form name = "myForm" action="someURL" onsubmit = "return validateForm();" method = "post">
Email: <input type="text" name="email">
<input type = "submit" value="Submit">
</form> 
</body></html>
-----------------------------
<html><head><script type="text/javascript">
function timeMsg(){
  var t = setTimeout("alertMsg()",3000);
}
function alertMsg() {
  alert("Hello");
}
</script></head><body>
<form>
<input type = "button" 
value = "Display alert box in 3 seconds"
onclick = "timeMsg()" />
</form>
</body></html>
-----------------------------
<html><head><script type="text/javascript">
var c = 0;
var t;
var timer_is_on = 0;
function timedCount(){
document.getElementById('txt').value = c;
c = c + 1;
t = setTimeout("timedCount()",1000);
}
function doTimer(){
if (!timer_is_on)
  {
  timer_is_on = 1;
  timedCount();
  }
}
</script></head><body>
<form>
<input type = "button" value = "Start count!" onclick="doTimer()">
<input type = "text" id="txt" />
</form>
</body></html>
-----------------------------
<html><head><script type="text/javascript">
var c = 0;
var t;
var timer_is_on = 0;
function timedCount(){
document.getElementById('txt').value=c;
c = c + 1;
t = setTimeout("timedCount()",1000);
}
function doTimer(){
if (!timer_is_on)
  {
  timer_is_on = 1;
  timedCount();
  }
}
function stopCount()
{
clearTimeout(t);
timer_is_on = 0;
}
</script></head><body>
<form>
<input type = "button" value="Start count!" onclick = "doTimer()">
<input type = "text" id="txt">
<input type = "button" value="Stop count!" onclick = "stopCount()">
</form>
</body></html>
----------------
person = new Object();
person.firstname = "John";
person.lastname = "Doe";
person.age = 30;
person.eyecolor = "blue";
document.write(person.firstname);
--------------------------
person= {firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};
document.write(person.firstname);
--------------------------
x.innerHTML - the text value of x
x.nodeName - the name of x
x.nodeValue - the value of x
x.parentNode - the parent ode of x
x.childNodes - the child nodes of x
x.attributes - the attributes nodes of x
-------------------------------------------------
x.getElementById(id) - get the element with a specified id
x.getElementsByTagName(name) - get all elements with a specified tag name
x.appendChild(node) - insert a child node to x
x.removeChild(node) - remove a child node from x
-------------------------------------------------
<html><body>
<p id = "intro">Hello World!</p>
<script type="text/javascript">
txt = document.getElementById("intro").innerHTML;
document.write("<p>The text from the intro paragraph: " + txt + "</p>");
</script></body></html>
------------------------------------
<html><body>
<p id="intro">Hello World!</p>
<script type="text/javascript">
txt= document.getElementById("intro").childNodes[0].nodeValue;
document.write("<p>The text from the intro paragraph: " + txt + "</p>");
</script>
</body></html>
------------------------------------
<html><body>
<p>Hello World!</p>
<p>The DOM is very useful!</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method.</p>
<script type="text/javascript">
x = document.getElementsByTagName("p");
document.write("Text of first paragraph: " + x[0].innerHTML); //Hello World! 
</script>
</body></html>
-----------------------------
<html><body>
<p>Hello World!</p>
<div id = "main">
<p>The DOM is very useful.</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method</p>
</div>
<script type="text/javascript">
x = document.getElementById("main").getElementsByTagName("p");
document.write("First paragraph inside the div: " + x[0].innerHTML);
//The DOM is very useful.
</script>
</body></html>
-------------------------------------------------
<html><body>
<p>Hello World!</p>
<p>The DOM is very useful!</p>
<script type="text/javascript">
x = document.getElementsByTagName("p");
document.write("Text of second paragraph: " + x[1].innerHTML);
</script>
</body></html>
-------------------------------------------------
<html><body>
<p id="intro">Hello World!</p>
<script type="text/javascript">
x = document.getElementById("intro");
document.write(x.firstChild.nodeValue);
//Hello World!
</script>
</body></html>
-------------------------------------
<html><body>
<script type="text/javascript">
document.body.bgColor="lavender";
</script>
</body></html> 
-------------------------------------
<html><body>
<p id="p1">Hello World!</p>
<script type="text/javascript">
document.getElementById("p1").innerHTML="New text!";
</script>
</body></html> 
--------------------------------------------------
<html><body>
<input type="button"
onclick = "document.body.bgColor = 'lavender'; "
value = "Change background color"  />
</body></html>
--------------------------------------------------
<html><head><script type="text/javascript">
function ChangeText(){
document.getElementById("p1").innerHTML = "New text!";}
</script></head><body>
<p id="p1">Hello world!</p>
<input type="button" 
onclick = "ChangeText()" value = "Change text" />
</body></html> 
--------------------------------------------------
<html><head><script type="text/javascript">
function ChangeBackground(){
document.body.style.backgroundColor="lavender";}
</script></head><body>
<input type="button" 
onclick = "ChangeBackground()"
value = "Change background color" />
</body></html> 
--------------------------------------------------
<html><head><script type="text/javascript">
function ChangeStyle(){
document.getElementById("p1").style.color="blue";
document.getElementById("p1").style.fontFamily="Arial";}
</script></head><body>
<p id = "p1">Hello world!</p>
<input type = "button" onclick = "ChangeStyle()" value = "Change style" />
</body></html> 
--------------------------------------------------
<html><head>
<script type="text/javascript">
function getEventType(event)
{
  alert(event.bubbles);
}
</script></head>
<body onmousedown = "getEventType(event)">
<p>Click somewhere in the document.
An alert box will tell if the
event is a bubbling event.</p>
</body></html> 
--------------------------------------
<html><head>
<script type="text/javascript">
function show_coords(event)
{
  var x = event.clientX
  var y = event.clientY
  alert("X coords: " + x + ", Y coords: " + y)
}
</script>
</head>
<body onmousedown = "show_coords(event)">
<p>Click in the document. An alert box will alert
the x and y coordinates of the mouse pointer.</p>
</body></html> 
--------------------------------------------------

No comments:

Post a Comment