Java Script
Java Script
Java Script
ILIJA DIVLJAN
JavaScript Notes
JAVASCRIPT................................................................................................................. 6
//output............................................................................................................. 6
//objects............................................................................................................ 6
ARRAYS....................................................................................................................... 6
//kreiranje niza.................................................................................................. 6
//mixedArray..................................................................................................... 6
//dodavanje elemenata..................................................................................... 6
//uklanjanje sa kraja.......................................................................................... 6
//dodavanje na kraj........................................................................................... 6
//brisanje sa pocetka......................................................................................... 7
//dodavanje na pocetak..................................................................................... 7
//dodavanje pocevsi od pozicije n.....................................................................7
//kopiranje elemenata iz jednog u drugi niz......................................................7
//provera da li je objekat Array..........................................................................7
STRINGS..................................................................................................................... 7
//toLowerCase() i toUpperCase().......................................................................7
//kopiranje dijela stringa....................................................................................7
//duzina stringa length...................................................................................... 8
//pronalazenje segmenta................................................................................... 8
//karakter na lokaciji.......................................................................................... 8
//Replacing characters...................................................................................... 8
NUMBERS................................................................................................................... 9
//zaokruzivanje brojeva..................................................................................... 9
//zaokruzivanje do najblizeg integera iznad (ceil).............................................9
//zaokruzivanje do najblizeg integera ispod (floor)............................................9
//generisanje slucajnih brojeva..........................................................................9
//Konvertovanje stringova u integere i decimalne brojeve................................9
//Konvertovanje stringova u brojeve, I brojeva u stringove...............................9
//Ogranicavanje broja decimala......................................................................10
DATE......................................................................................................................... 10
//trenutni datum I vrijeme...............................................................................10
//Date objekat I metode.................................................................................. 10
//specificiranje vremena i datuma...................................................................11
//Promena elemenata datuma I vremena........................................................11
FUNCTIONS............................................................................................................... 12
//tijelo funkcije................................................................................................ 12
//deklaracija funkcija....................................................................................... 12
//invokacija funkcija........................................................................................ 12
//konverzija farenhajta u celzijuse, primjer......................................................12
//opseg vazenja lokalne vs globalne varijable..............................................12
//switch........................................................................................................... 12
DODAVANJE SKRIPTI.................................................................................................. 13
//script tag....................................................................................................... 13
//externaj JavaScript........................................................................................ 14
EVENTS..................................................................................................................... 14
//inline eventing (link)..................................................................................... 14
//inline (button)............................................................................................... 15
//mouse events............................................................................................... 15
//field events................................................................................................... 15
//HTML/DOM events......................................................................................... 15
//event properties/methods/objects................................................................17
READING FIELD VALUES............................................................................................ 20
//provera vrednosti polja................................................................................. 20
//popunjavanje polja u formi........................................................................... 20
//citanje i postavljanje teksta u paragrafu (read more..).................................20
//manipulisanje tekstom I slikama...................................................................21
//zamjena slika................................................................................................ 21
//target elements by tag name.......................................................................21
THE DOM.................................................................................................................. 23
//The DOM: Parents and children.....................................................................23
//The DOM: Finding children............................................................................ 24
//The DOM: checking Node type......................................................................25
//The DOM: Dodatni nacini za dohvacanje elemanta (child nodes and siblings)
........................................................................................................................ 25
//The DOM: Dohvatanje imena cvora..............................................................26
//The DOM: Counting elements.......................................................................27
//The DOM: Atributi......................................................................................... 27
//The DOM: Citanje i postavljanje vrednosit atributa.......................................27
//The DOM: Dohvacanje imena i vrijednosti atributa.......................................27
JAVASCRIPT
var
var
var
var
length = 16;
// Number
lastName = "Johnson";
// String
cars = ["Saab", "Volvo", "BMW"];
// Array
x = {firstName:"John", lastName:"Doe"}; // Object
//output
//objects
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
ARRAYS
//kreiranje niza
var cities = ["Atlanta", "Baltimore", "New York", "Paris", "LA"];
for (var i = 0; i < cities.length; i++) {
console.log(cities[i]);
}
//mixedArray
var mixedArray = [1, "Bob", "Now is", true];
//dodavanje elemenata
var pets = [];
pets[0] = "dog";
pets[1] = "mouse";
pets[2] = "cat";
//uklanjanje sa kraja
pets.pop();
//dodavanje na kraj
pets.push(fish, shark);
//brisanje sa pocetka
pets.shift();
//dodavanje na pocetak
pets.unshift("addFirst", "addFirst");
//dodavanje pocevsi od pozicije n
pets.splice(2, 0, "dodaj2usred", "dodaj2usred");
Prvi argument predstavlja poziciju od koje se dodaju elementi. Drugi argument
predstavlja broj elemenata koji se brisu iz starog niza pocevsi od pozicije 2. Ako
zelimo samo brisanje onda pets.splice(2,1) => brise element na poziciji 2.
//kopiranje elemenata iz jednog u drugi niz
var newArray = pets.slice(2, 4)
cijeli niz => var newArray = pets.slice();
//provera da li je objekat Array
var fruits = ["Banana", "Orange", "Apple", "Mango"];
typeof fruits;
// returns object
The typeof operator returns object because a JavaScript array is an object.
Array.isArray(fruits);
To solve this problem you can create your own isArray() function:
function isArray(x) {
return x.constructor.toString().indexOf("Array") > -1;
}
ili
fruits instanceof Array
// returns true
STRINGS
//toLowerCase() i toUpperCase()
cityToCheck = cityToCheck.toLowerCase();
cityToCheck = cityToCheck.ToUpperCase();
//kopiranje dijela stringa
var firstChar = cityToCheck.slice(0, 1);
If cityToCheck is "Boston", firstChar is "B"
var someChars = cityToCheck.slice(2); If you omit the second number inside the
parentheses, JavaScript includes all the characters to the end of the string
//duzina stringa length
var month = prompt("Enter a month");
var charsInMonth = month.length;
//konverzija stringova u niz (String to an Array)
var txt = "a,b,c,d,e"; // String
txt.split(",");
// Split on commas
txt.split(" ");
// Split on spaces
txt.split("|");
// Split on pipe
txt.split("");
// Split in characters
//pronalazenje segmenta
for (var i = 0; i < text.length; i++) {
if (text.slice(i, i + 12) === "World War II") {
text = text.slice(0, i) + "the Second World War" + text.slice(i + 12);
}
}
Efikasnije je ovo rijesiti sa indexOf metodom
var firstChar = text.indexOf("World War II");
Ako je dati tekst sadrzan metod ce vratiti indeks prvog karaktera a ako ne vraca -1.
var firstChar = text.indexOf("World War II");
if (firstChar !== -1) {
text = text.slice(0, firstChar) + "the Second World War" + text.slice(firstChar
+ 12);
}
LasIndexOf() pronalazi poziciju prvog slova u poslednjem ponavljanju fraze.
//karakter na lokaciji
var firstChar = firstName.charAt(x)
//Replacing characters
Moze koristenjem metoda slice ili indexOf ali je efikasnije sa replace.
var newText = text.replace("World War II", "the Second World War");
Ovo mijenja prvo ponavljanje, ako zelimo svako ponavljanje u tekstu moramo
koristiti backslash i g.
NUMBERS
//zaokruzivanje brojeva
var numberOfStars = Math.round(scoreAvg);
//zaokruzivanje do najblizeg integera iznad (ceil)
var scoreAvg = Math.ceil(.000001); rezultat je 1
//zaokruzivanje do najblizeg integera ispod (floor)
var scoreAvg = Math.floor(.999999);
//generisanje slucajnih brojeva
The following code generates a pseudo-random number, with 16 decimal places,
ranging from 0.0000000000000000 through 0.9999999999999999 and assigns it to
the variable randomNumber.
var randomNumber = Math.random();
The function always delivers a 16-place decimal that ranges from
0.0000000000000000 to 0.9999999999999999. We can convert the decimal to an
integer by multiplying by one hundred quadrillion (1 followed by 17 zeroes).
Trillions of possible numbers are more than we need in our virtual die throw. We just
want six possible numbers, 1 through 6. So instead of multiplying by a hundred
quadrillion, our first step is to multiply the giant decimal by 6. But we can give all
the numbers an equal chance if we add 1 to the result, then round down.
//Konvertovanje stringova u integere i decimalne brojeve
var currentAge = prompt("Enter your age.");
var qualifyingAge = parseInt(currentAge) + 1;
za (-, *, /) javascript automatski prevodi, za + vrsi konkatenaciju stringova, zato se
koristi parseInt(ca)
var myFractional = parseFloat("1.9999");
//Konvertovanje stringova u brojeve, I brojeva u stringove
var integerString = "24"
var num = Number(integerString); (num = 24)
var floatingNumString = "24.9876";
var num = Number(floatingNumString); (num = 24.9876)
var numberAsNumber = 1234;
var numberAsString = numberAsNumber.toString();
DATE
//trenutni datum I vrijeme
var rightNow = new Date();
//Date objekat I metode
FUNCTIONS
//tijelo funkcije
function greetUser() {
alert("Hello, there.");
}
function myFunction(p1, p2) {
return p1 * p2;
// The function returns the product of p1 and p2
}
//deklaracija funkcija
function name(parameter1, parameter2, parameter3) {
code to be executed
}
//invokacija funkcija
code block
break;
default:
default code block
}
switch (new Date().getDay()) {
case 1:
case 2:
case 3:
default:
text = "Looking forward to the Weekend";
break;
case 4:
case 5:
text = "Soon it is Weekend";
break;
case 0:
case 6:
text = "It is Weekend";
}
DODAVANJE SKRIPTI
All of your JavaScript functions, for example, are loaded into memory when the page
loads. Wherever the code may be, the browser finds it and stores it by the time the
page is finished loading. Once the page is loaded, all the JavaScript code stays in
memory, ready to execute, for as long as the page is displayed. You can legally put
JavaScript code almost anywhere in the HTML filein the head section, at the
beginning of the body section, somewhere in the middle of the body section, or at
the end of the body section. You could, if you wanted to be perverse, sprinkle
different Javascript functions all over your HTMLfile in different places. The browser
would sort it all out.
Generally, the best place for scripts, though, is at the end of the body section.
This guarantees that CSS styling and image display won't get held up while scripts
are loading. When you embed blocks of JavaScript in HTML (as opposed to having a
separate JavaScript file), you must enclose the JavaScript code between <script>
and </script> tags. Here are two functions enclosed between the tags.
//script tag
<!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
EVENTS
//inline eventing (link)
<a href="#" onClick="alert('Hi');">Click</a>
<button onclick="this.innerHTML=Date()">The time is?</button>
When the user clicks the link, you don't want a new webpage to be loaded in this
case, so, instead of a URL, you place a # inside the quotation marks. This tells the
browser to reload the current page. But there's a problem with the markup above.
<a href="#" tells the browser to reload the page. This means that if the user has
scrolled down to the link, the click, in addition to running the JavaScript code, will
scroll the page back to the topan action you don't normally want. I've included
this flawed approach, but youll probably prefer this approach:
<a href="JavaScript:void(0)" onClick="alert('Hi');">Click</a> //ne ucitava stranicu
ponovo
<a href="JavaScript:void(0)" onClick="var greet="hi'; alert(greet);">Click</a>
Generally you will define a new function and pass it as a event handler:
function popup(message) {
alert(message);
}
<a href="JavaScript:void(0)" onClick="popup('Hi');">Click</a>
//inline (button)
<input type="button" value="Click" onClick="alert('Hello world!');">
Some pros would argue that the button code should be enclosed in form tags, but
it's not absolutely necessary. And anyway, since we're already violating best
practices by using inline event handlers, why not scandalize the pros with multiple
violations?
<a href="summary-page.html"><img src="button-sum-pg.png"></a>
<img src="button-greet.png" onClick="alert('Hello world!');">
<img src="button-greet.png" onClick="greetTheUser();">
//mouse events
<a href="index.html" onMouseover="this.style.color='green';">Home Page</a>
<p id="loris" onMouseover="expand();">Slow Loris: Mouse over for more info</p>
<img src="before-pic.jpg" onMouseover="src='after-pic.jpg'"
onMouseout="src='before-pic.jpg'">
<input type="button" value="Panic" onMouseover="alert('Eeek!');"/>
//field events
<input type="text" size="30" onFocus="this.style.backgroundColor='yellow';">
<input type="text" size="30" onFocus="this.style.backgroundColor='yellow';"
onBlur="this.style.backgroundColor='white';">
//HTML/DOM events
//event properties/methods/objects
Almost anything, including HTML tags, can be inserted into the web page this way.
For example, you could make this list appear on the page within, say, a div with the
id "lorisList".
Dodavanje na ovakav nacin prebrise postojecu klasu DOM elementa, ako hocemo da
dodamo jos jednu klasu onda vrsimo jednostavno konkatenaciju stringova, na
sledeci nacin:
//zamjena slika
THE DOM
The DOM is an organization chart, created automatically by the browser when your
web page loads, for the whole web page. All the things on your web pagethe tags,
the text blocks, the images, the links, the tables, the style attributes, and more
have spots on this organization chart. This means that your JavaScript code can get
its hands on anything on your web page, anything at all, just by saying where that
thing is on the chart. What's more, your JavaScript can add things, move things, or
delete things by manipulating the chart
In this particular chart, there are three types of nodes: document, element, and
text. The document node is the top level. Element nodes are <html>, <head>,
<body>, <title>, <div>, and <p>. Text nodes are the strings that comprise the title
and the two paragraphs.
//The DOM: Parents and children
You can designate any node of the DOM by saying the node is the xth child of a
particular parent. You can also designate a node by saying it's the parent of any
child. When a node is enclosed within another node, we say that the enclosed node
is a child of the node that encloses it. So, for example, the <div> node is a child of
the <body> node. Conversely, the <body> node is the parent of the <div> node.
Here's the organization chart from the last chapter, again cleaned of junk artifacts,
showing all the parents and their children.
<p>This is <em>important</em>!</p>
var d = document.getElementById("humpty");
var pCounter = 0;
//The DOM: Dodatni nacini za dohvacanje elemanta (child nodes and siblings)
var targetNode = parentNode.childNodes[0];
var targetNode = parentNode.firstChild;
var targetNode = parentNode.lastChild;
var pNode = kidNode.parentNode;
You can use nextSibling and previousSibling to target the next child and the
previous child in the collection of an element's children. In the following code, the
first statement targets a div with the id "div1". The second statement targets the
next node that has the same parent as the "div1" id.
var firstEl = document.getElementById("div1");
secondEl = firstEl.nextSibling;
If there is no nextSibling or previousSibling, you get null. In the following code, the
variable nonexistentEl has a value of null, because JavaScript finds that there is no
previous node that has the same parent as firstEl.
var firstEl = document.getElementById("div1");
var nonexistentEl = firstEl.previousSibling;
Once again, I'll say that you're often better off assigning an id to any node you
might want to "read" or change. Then you can target the node more directly, using
document.getElementById.
//The DOM: Dohvatanje imena cvora
In a previous chapter you learned how to get a node's node type with a statement
like this.
var nType = targetNode.nodeType;
You can get additional information about a node by using nodeName. In the
following example, the node name of the target node is assigned to the variable
nName.
On the other hand, if the node is a text node, the name of the node is always #text
in lower-case. If it's a text node, you can find out its valuei.e. its contentthis
way:
var nTextContent = target.nodeValue;
It's possible to confuse the node value of a text node with the innerHTML property.
There are two differences.
You can find out whether an element has a particular attribute with hasAttribute.
...the variable nName is assigned "onMouseover". You can also get the value of the
attribute...
var nValue = list[2].nodeValue;
//The DOM: Dodavanje cvorova
Using the DOM hierarchy, you can add element, attribute, and text nodes anywhere
in the head or body sections of a document. In this chapter you'll learn how to
create a paragraph node, give it an attribute, and fill it with text content. In the next
chapter, you'll learn how to insert the paragraph, along with its attributes and text
content, into the page.
The first step is to create the paragraph node.
var nodeToAdd = document.createElement("p");
The example creates a paragraph element. To create a div element, you'd put "div"
in the parentheses. To create an image element, you'd put "img" there. To create a
link, you'd put "a" there. And so on.
nodeToAdd.setAttribute("class", "regular");
imgNodeToAdd.setAttribute("border", "1");
Now let's give it some text content. Again, we begin by creating the node we want.
var newTxt = document.createTextNode("Hello!");
nodeToAdd.appendChild(newTxt);
//The DOM: Inserting nodes
In the last chapter you learned how to add text content to an element by first
creating a text node and then appending the node to the element with appendChild.
You can of course use the same method to append the paragraph element itself,
filled with content or not, to a parent node, for example the body or a div. This set of
statements targets a div (line 1), creates a new paragraph element (line 2), creates
the text to go in it (line 3), places the text into the paragraph (line 4) and then
appends the paragraph element along with its text content to the targeted div (line
5).
For example, suppose you want the paragraph to be the first one in the div, rather
than the last.
There is no insertAfter method as such. But you can still do it. Simply insertBefore
the target node's next sibling.
By inserting the new node before the next sibling of the second child, you insert the
new node after the second child. To remove a node use removeChild
OBJECTS
//Tips and tricks with properties
If you want to create a property now and assign it a value later, you can create it
with a value of undefined.
deal3.market = undefined;
You can delete a property of an object
delete deal3.market;
You can check to see if a property of an object exists. The following statement tests
whether there is such a thing as deal3.market and assigns the result (true or false)
to the variable propertyExists.
propertyExists = "market" in deal3;
//Creating objects
Poziv funkcije:
var annualPrice = plan1.calcAnnual(.85);
U prethodnom primjeru ne koristiti naziv objekta plan1 vec kljucnu rijec this.
//Objects constructors
Kreiranje objekata na prethodno specificiran nacin je lose jer ako zelimo vise
objekata moramo replicirati kod. Zato se koriste fabrike:
The function name is capitalized. JavaScript doesn't care whether you do this
or not, but it's conventional to do it to distinguish constructor functions from
regular functions.
Each of the parameter values is assigned to a variable. But the variable is a
property attached to some object whose name hasn't been specified yet. But
don't worry. Just as the parameter values will be filled in by the calling code,
so will the name of the object.
This would be just a regular function call if it weren't for that new. It's the keyword
that tells JavaScript to create a new object. The name of the new object is plan1. Its
properties are enumerated inside the parentheses. Now it's easy to mass-produce
as many objects as you want, using the same pattern
//PROTOTYPES
Razliciti objekti a svi koriste istu funkciju koja je djeljena medju njima.
We want only one copy of the method, shared by all objects created with the
constructor, no matter how many objects are created. How do we do it? With a
prototype statement. First, we don't include the method in the constructor function,
because that creates a copy of the method for every single object that's created
with the constructor. Instead, we define the method as a prototype of the
constructor, this way.
Now, all objects created with the constructor Plan will share the same copy of the
method calcAnnual. There's no unnecessary duplication. Note that except for the
first line, the method is coded exactly as I coded it when it was part of the
constructor definition.
Objects can have prototype properties as well as prototype methods. Suppose you
wanted all objects created with the Plan to share the same property, cancellable,
with a value of true. You'd code the prototype this way.
Plan.prototype.cancellable = true;
It's possible to override a prototype for any individual object. For example, suppose
you want all objects created with the constructor to share the same cancellable
property, except for the least expensive plan, plan1, with the name "Basic." This is
the statement that does it
plan1.cancellable = false;
//Object hasOwnProperty
Ova for petlja iterira kroz propertije objekta plan1 I u niz dodaje samo licne
propertije objekta, ne one koje je naslijedio od prototipa.
BROWSER CONTROL
//Getting and setting the URL IMPORTANT
http://www.mybeautifulsite.com/products/page33.html#humidifier
In addition to making things happen on the webpage, you can use JavaScript to
control the browser. To begin with, you can get the browser to tell you its current
location.
var whereWeAt = window.location.href;
You can also get pieces of this. This statement gets just the domain name.
var theDomain = window.location.hostname;
In the example, the string "www.mybeautifulwebsite.com" is assigned to the
variable theDomain. "http://", the path, and the anchor are omitted.
var thePath = window.location.pathname;
In the example, the string "/products/page33.html" is assigned to the variable
thePath. If the browser were on the home page and the URL were simply
http://www.mybeautifulsite.com, the string "/" would be assigned to the variable.
In the example, the browser has been pointed to a section of the page marked by
the anchor #humidifier. If there is no anchor in the URL, the variable is assigned an
empty string, "". This statement identifies the anchor:
var theAnchor = window.location.hash;
Suprotan postupak, postavljanje vrijednosti:
window.location.href = "http://www.me.com/1.html#section9";
Jos jedan nacin je pomocu replace ali u ovom slucaju se trenutna strana brise iz
istorije I nece biti dostupna npr za backspace:
//Reloading a page
To reload the current page code one of these statements:
All three statements reload the current page. If the argument is true (example 1
above), the statement forces the browser to load the page from the server. If the
argument is false (example 2) or if there is no argument (example 3), the browser
will load the page from the cache if the page has been cached.
//Browser control: Forward and reverse
history.back();
history.forward();
You can tell the browser how many steps in the history you want to take, using
negative numbers to go back and positive numbers to go forward. The following
statement is the equivalent of pressing the Backspace key three times.
history.go(-3);
If the user clicked a link to get to the current page, you can get the URL of the page
where the link was clicked.
var whereUserCameFrom = document.referrer;
However, this works only if a link was clicked, including a link in a search result. If
the user got to your page through a bookmark or by entering your URLin the
address bar, the result of document.referrer will be an empty string, "".
//Browser control: Filling the window with content, popup windows
This chapter and the next one teach you the code that creates the window.
var monkeyWindow = window.open();
The code above opens a blank window of maximum size and gives it a handle, a
variable that refers to this particular windowin this case, monkeyWindow.
Depending on the browser, the window may open on top of the previous window, in
a new tab, or even in a new copy of the browser. You can't control this.
There are three ways to fill a new window with content, You can use the write
method to put HTML content on the screen...
The second way to fill the window with content is to assign a document to it, as you
learned to do in previous chapters.
var monkeyWindow = window.open();
monkeyWindow.location.assign("test.html");
or
monkeyWindow.location.href = "test.html";
The third and most common way to fill the window content is to include the
document assignment in the statement that opens the window.
var monkeyWindow = window.open("test.html");
This is how you close a window.
monkeyWindow.close();
Ovako prosledjujemo sirinu i visinu:
var monkeyWindow = window.open("test.html", "win1", "width=420,height=380");
//Browser control: Testing for popup blockers
Popup blockers are now a standard feature of browsers, with some level of popup
blocking usually built in as a default. JavaScript popups, and especially those that
open a new page within the same website, are often tolerated by default, but you
can never be sure. If popups are an essential feature of your site, you need to test
whether your popups are going to be blocked. If they are, you can ask the user to
disable the popup blocker for your site.
FORM VALIDATION
//Form validation: text fields
When the user clicks the Submit button, the function checkForLastName is called.
Here's the function.
The Boolean value false is returned to the calling code. This prevents the form from
being submitted. In order for the submission to be called off, there has to be a
matching keyword return in the markup that calls the function. Without this return in
the calling code, the return in line 7 of the function won't stop the form from being
submitted.
The sample code in this chapter targets forms and fields by ID, which is the most
straightforward approach. But you could target by name, by tag, or by position in
the DOM hierarchy. Instead of hard-wiring the ID into the function, you could
potentially make it multi-use by naming the field ID as a parameter, and passing the
ID to it from the calling code.
//Form validation: drop-downs
Function
Note that the radio buttons all have the same name, "r1". This is the validating
function that checks to see if the user has clicked one of the buttons.
IsNaN => is not a number, posto zip ima samo cifre, testiramo da li nije broj I
vracamo upozorenje.
//Form validation: email
Validating an email field includes checking to make sure there are no illegal
characters, like spaces, and that all the essentials of a legal email address are
there: one or more characters, followed by @, followed by one or more characters,
followed by a dot, followed by two to four characters. The standard way to test for
all this is to match the user's entry with a regular expression.
TRY CATCH
Ovde je pukla kljucna rijec alert jer je pogresno napisana kao aler.
//Exceptions: throw
By adding one or more throw statements, you can define your own errors in a
try...catch pair. This can be useful for dealing with wayward user behavior. Suppose
you've asked the user to create a password. It must be at least 8 to 12 characters
long, must contain at least one number, and can't contain any spaces. This is the
markup that creates the form, simplified to keep you focused on the essentials:
U opadajucem:
points.sort(function(a, b){return b - a});
//Sortiranje objekata
var cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}];
cars.sort(function(a, b){return a.year - b.year});
Type Conversion
//typeof Operator
// returns 0
// returns 1
//Input validation
<body>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="message"></p>
<script>
function myFunction() {
var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "empty";
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x < 5) throw "too low";
if(x > 10) throw "too high";
}
catch(err) {
message.innerHTML = "Input is " + err;
}}</script></body>
//DEBUGGING
In the debugger window, you can set breakpoints in the JavaScript code.
The debugger keyword stops the execution of JavaScript, and calls (if available)
the debugging function.
//BEST PRACTICES
var x = "John";
var y = new String("John");
(x === y) // is false because x is a string and y is an object
var
var
var
var
var
var
var
x1
x2
x3
x4
x5
x6
x7
=
=
=
=
=
=
=
{};
// new object
"";
// new primitive string
0;
// new primitive number
false;
// new primitive boolean
[];
// new array object
/()/;
// new regexp object
function(){}; // new function object
the value of the missing argument is set to undefined. Undefined values can
break your code. It is a good habit to assign default values to arguments.)
function myFunction(x, y) {
if (y === undefined) {
y = 0;
}
}
//JAVASCRIPT PERFORMANCE
Reduce activity in loops
JSON
This JSON syntax defines an employees object: an array of 3 employee records
(objects):
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}
The JSON format is syntactically identical to the code for creating JavaScript objects.
Because of this similarity, a JavaScript program can easily convert JSON data into
native JavaScript objects.
//JSON Objects
{"firstName":"John", "lastName":"Doe"}
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<a href="' + arr[i].url + '">' +
arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>
JAVASCRIPT REGEX
A regular expression is a sequence of characters that forms a search pattern.
When you search for data in a text, you can use this search pattern to describe what
you are searching for. A regular expression can be a single character, or a more
complicated pattern. Regular expressions can be used to perform all types of text
search and text replace operations.
/pattern/modifiers;
var patt = /w3schools/i;
Since there is an "e" in the string, the output of the code above will be true
AJAX
AJAX = Asynchronous JavaScript and XML. AJAX allows web pages to be updated
asynchronously by exchanging small amounts of data with the server behind the
scenes. This means that it is possible to update parts of a web page, without
reloading the whole page.
Classic web pages, (which do not use AJAX) must reload the entire page if the
content should change.
Examples of applications using AJAX: Google Maps, Gmail, YouTube, and Facebook.
//XMLHttpRequest
The XMLHttpRequest object is used to exchange data with a server behind the
scenes. This means that it is possible to update parts of a web page, without
reloading the whole page. All modern browsers (Chrome, IE7+, Firefox, Safari, and
Opera) have a built-in XMLHttpRequest object.
Syntax for creating an XMLHttpRequest object:
To handle all browsers, including IE5 and IE6, check if the browser supports the
XMLHttpRequest object. If it does, create an XMLHttpRequest object, if not, create
an ActiveXObject:
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//AJAX Request
To send a request to a server, we use the open() and send() methods of the
XMLHttpRequest object:
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
GET is simpler and faster than POST, and can be used in most cases. However,
always use POST requests when:
To POST data like an HTML form, add an HTTP header with setRequestHeader().
Specify the data you want to send in the send() method:
xhttp.open("POST", "ajax_test.asp", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Henry&lname=Ford");
//Server Response
document.getElementById("demo").innerHTML = xhttp.responseText;
xmlDoc = xhttp.responseXML;
txt = "";
x = xmlDoc.getElementsByTagName("ARTIST");
for (i = 0; i < x.length; i++) {
txt += x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("demo").innerHTML = txt;
//OnReadyStateChange
The onreadystatechange event is triggered every time the readyState changes. The
readyState property holds the status of the XMLHttpRequest. Three important
properties of the XMLHttpRequest object:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
//AJAX ASP
<html>
<head>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "gethint.asp?q=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<p><b>Start typing a name in the input field below:</b></p>
<form>
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
<%
response.expires=-1
dim a(30)
'Fill up array with names
a(1)="Anna"
a(2)="Brittany"
a(3)="Cinderella"
a(4)="Diana"
a(5)="Eva"
a(6)="Fiona"
a(7)="Gunda"
a(8)="Hege"
a(9)="Inga"
a(10)="Johanna"
a(11)="Kitty"
a(12)="Linda"
a(13)="Nina"
a(14)="Ophelia"
a(15)="Petunia"
a(16)="Amanda"
a(17)="Raquel"
a(18)="Cindy"
a(19)="Doris"
a(20)="Eve"
a(21)="Evita"
a(22)="Sunniva"
a(23)="Tove"
a(24)="Unni"
a(25)="Violet"
a(26)="Liza"
a(27)="Elizabeth"
a(28)="Ellen"
a(29)="Wenche"
a(30)="Vicky"
'get the q parameter from URL
q=ucase(request.querystring("q"))
'lookup all hints from array if length of q>0
if len(q)>0 then
hint=""
for i=1 to 30
if q=ucase(mid(a(i),1,len(q))) then
if hint="" then
hint=a(i)
else
hint=hint & " , " & a(i)
end if
end if
next
end if
'Output "no suggestion" if no hint were found
'or output the correct values
if hint="" then
response.write("no suggestion")
else
response.write(hint)
end if
%>
//AJAX DATABASE
//AJAX XML FILE