Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java Script

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 60
At a glance
Powered by AI
The document discusses JavaScript concepts like arrays, strings, numbers, dates and objects.

Strings, numbers, arrays, objects and dates are covered as JavaScript data types.

Methods for creating, adding/removing elements from arrays and copying arrays are discussed.

JAVASCRIPT IN A NUTSHELL

ILIJA DIVLJAN

FIS | Milutina Milankovica 136b

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

//The DOM: Dodavanje cvorova.......................................................................27


//The DOM: Inserting nodes.............................................................................28
OBJECTS................................................................................................................... 29
//Tips and tricks with properties......................................................................29
//Creating objects............................................................................................ 29
//Objects constructors..................................................................................... 29
//PROTOTYPES................................................................................................. 31
//Object hasOwnProperty................................................................................ 32
BROWSER CONTROL................................................................................................. 33
//Getting and setting the URL IMPORTANT.......................................................33
//Getting and setting the URL another way.....................................................33
//Reloading a page.......................................................................................... 34
//Browser control: Forward and reverse..........................................................34
//Browser control: Filling the window with content, popup windows................34
//Browser control: Testing for popup blockers.................................................35
FORM VALIDATION.................................................................................................... 36
//Form validation: text fields........................................................................... 36
//Form validation: drop-downs.........................................................................36
//Form validation: radio buttons......................................................................37
//Form validation: zip code..............................................................................37
//Form validation: email..................................................................................38
TRY CATCH................................................................................................................ 39
//Exceptions: throw......................................................................................... 39
W3C TUTORIAL ADDITIONS................................................................................... 40
//Sorting an Array............................................................................................ 40
//Numeric sort................................................................................................. 40
//Random sortiranje......................................................................................... 40
//Sortiranje objekata........................................................................................ 40
Type Conversion.................................................................................................... 41
//typeof Operator............................................................................................ 41
//If object is Array............................................................................................ 41
//If object is date............................................................................................. 41
//String/Boolean to Number conversion..........................................................41
//Input validation............................................................................................. 41

//JavaScript Type Conversion Table..................................................................42


//DEBUGGING.................................................................................................. 42
JavaScript Best Practices....................................................................................... 43
//Java script Strict Mode..................................................................................43
//Style guidelines............................................................................................. 43
//BEST PRACTICES........................................................................................... 43
//Test if object exists........................................................................................ 44
//JAVASCRIPT PERFORMANCE...........................................................................45
//HTML EVENT HANDLERS............................................................................... 45
//JavaScript Objects, Properties, and Methods.................................................46
JSON...................................................................................................................... 46
//JSON Objects................................................................................................. 46
//Converting a JSON Text to a JavaScript Object..............................................46
//JSON HTTP REQUEST..................................................................................... 46
JAVASCRIPT REGEX................................................................................................ 48
JAVASCRIPT W3SCHOOLS REFERENCE......................................................................50
AJAX.......................................................................................................................... 51
//XMLHttpRequest........................................................................................... 51
//AJAX Request................................................................................................ 52
//Server Response........................................................................................... 53
//OnReadyStateChange...................................................................................53
//AJAX ASP....................................................................................................... 54
//AJAX DATABASE............................................................................................. 56
//AJAX XML FILE............................................................................................... 56

PAGE INTENTIONALLY LEFT BLANK

JAVASCRIPT
var
var
var
var

length = 16;
// Number
lastName = "Johnson";
// String
cars = ["Saab", "Volvo", "BMW"];
// Array
x = {firstName:"John", lastName:"Doe"}; // Object

//output

Writing into an alert box, using window.alert()

Writing into the HTML output using document.write()


Writing into an HTML element, using innerHTML

Writing into the browser console, using console.log()

//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);

// returns true (ne radi u starijim web citacima) ECMAScript5

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.

var newText = text.replace(/World War II/g, "the Second World War");

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();

//Ogranicavanje broja decimala


var prettyTotal = total.toFixed(2);
var prettyTotal = total.toFixed();
Problem je sto toFixed() radi zaokruzivanje, I to zavisi od browsera toFixed(1.555)
moze negdje dati 1.56 ili 1.55. Zato se to rjesava koristenjem if-a:
if (str.charAt(str.length - 1) === "5") {
str = str.slice(0, str.length - 1) + "6";
}

DATE
//trenutni datum I vrijeme
var rightNow = new Date();
//Date objekat I metode

//specificiranje vremena i datuma


var d = new Date("July 21, 1983 13:25:00");
var doomsday = new Date("June 30, 2035");
var msToday = today.getTime();
var msDoomsday = doomsday.getTime();
var msDiff = msDoomsday - msToday; //rezultat u milisekundama
var dDiff = msDiff / (1000 * 60 * 60 * 24); //rezultat u danima
odnosno
var msDiff = new Date("June 30, 2035").getTime() - new Date().getTime();
var daysTillDoom = Mathfloor(msDiff / (1000 * 60 * 60 * 24));
//Promena elemenata datuma I vremena

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

Kada se desi dogadjaj (click na primjer)


Kada se funkcija pozove iz JavaScript koda
Autmatski (self invoked)

//konverzija farenhajta u celzijuse, primjer


function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius(77);
//opseg vazenja lokalne vs globalne varijable
// code here can not use carName
function myFunction() {
var carName = "Volvo";
// code here can use carName
}
var carName = " Volvo";
// code here can use carName
function myFunction() {
// code here can use carName
}
//switch
switch(expression) {
case n:
code block
break;
case n:

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>

<p id="demo">A Paragraph</p>


<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
//externaj JavaScript
<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>
You can place an external script reference in <head> or <body> as you like.

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

READING FIELD VALUES


//provera vrednosti polja
<form onSubmit="checkAddress('email');">
Email:
<input type="text" id="email">
<input type="submit" value="Submit">
</form>
function checkAddress(fieldId) {
if (document.getElementById(fieldId).value === "") {
alert("Email address required.");
}
}
//popunjavanje polja u formi

//citanje i postavljanje teksta u paragrafu (read more..)

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

//manipulisanje tekstom I slikama


Ako hocemo da slika postane nevidljiva na klik misa

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

//target elements by tag name

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>

//The DOM: Finding children


var eField = document.getElementById("email");
var eField = document.getElementsByTagName("p");
Dohvacanje sadrzaja iz kolekcije paragrafa: var contents = p[2].innerHTML;
The statement above assigns the text string contained within the third paragraph of
the document to the variable contents.

Elementi se mogu dohvacati I koristenjem DOM strukture, na primjer na sledeci


nacin

//The DOM: checking Node type


Osnovni problem je jer neki web citaci u DOM strukturu ukljucuju i prazna mjesta
(tabove) koji se koriste za pravilno formatiranje HTML koda. Iz toga razloga npr div
tag koji ima 3 p elementa, ima dodatne child elemente koji su text tipa i nastaju kao
posledica koristenja taba. Sada taj div ima vise od 3 child elementa I njihovo
pretrazivanje nije jednostavno. Ovo se moze rijesiti koristenjem minimizer
biblioteka, koje uklanjaju sva prazna mjesta, ili JavaScript provjerom.
JavaScript can check a node to see what type it iselement, text, comment, and so
on. For example, this statement checks the node type of a targeted node and
assigns it to the variable nType.
var nType = targetNode.nodeType;
In the statement above, JavaScript assigns a number representing the
node type to the variable nType. If the node is an element like <div> or
<p>, the number is 1. If it's a text node, the number is 3.
Suppose you want to replace the text content of the second paragraph in a
particular div with the string "All his men." Here's the markup, with the text we're
going to change highlighted.

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.

innerHTML is a property of the element node, <h2>, in the above example.


The node value is a property of the text node itself, not the parent element.
innerHTML includes all the descendants of the element, including any inner
element nodes like <em> as well as text nodes. The node value includes only
the characters that comprise the single text node.

if (targetNode.nodeName.toLowerCase === "img") {}


//The DOM: Counting elements
var liElements = getElementsByTagName("li");
var howManyLi = liElements.length;

//The DOM: Atributi

You can find out whether an element has a particular attribute with hasAttribute.

//The DOM: Citanje i postavljanje vrednosit atributa

//The DOM: Dohvacanje imena i vrijednosti atributa


var list = document.getElementById("p1").attributes;
Using array-like notation, you can find out the name of any attribute in the
collection. The following statement targets the third item in the collection of
attributes and assigns its name to the variable nName.
var nName = list[2].nodeName;
For example, if the markup is... <p id="p1" class="c1"
onMouseover="chgColor();">

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

This would be a plain-vanilla function definition but for two differences:

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

U slucaju da funkcija ima metode isti je postupak

//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";

//Getting and setting the URL another way

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.

Normally, you'd run the test when the page loads.


<body onLoad ="checkForPopBlocker();">

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

In this case the form is: <form onSubmit="return checkForSelection('states');">

//Form validation: radio buttons

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.

//Form validation: zip code

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.

var regex = /^[\w\-\.\+]+\@[a-zA-Z0-9\. \-]+\.[a-zA-z0-9]{2,4}$/;

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:

W3C TUTORIAL ADDITIONS


//Sorting an Array
The sort() method sorts an array alphabetically:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
// Sorts the elements of fruits
The reverse() method reverses the elements in an array.
fruits.reverse();
//Numeric sort
Ovde je potrebno obezbjediti compare funkciju jer sort() sortira alfabetski pa je 25 >
100.
U rastucen poretku:
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});

U opadajucem:
points.sort(function(a, b){return b - a});

The purpose of the compare function is to define an alternative sort order.


//Random sortiranje
points.sort(function(a, b){return 0.5 - Math.random()});

//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});

Poredjenje string propertija:


cars.sort(function(a, b){
var x = a.type.toLowerCase();
var y = b.type.toLowerCase();
if (x < y) {return -1;}
if (x > y) {return 1;}
return 0;
});

Type Conversion
//typeof Operator

//If object is Array


function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}

//If object is date


function isDate(myDate) {
return myDate.constructor.toString().indexOf("Date") > -1;
}

//String/Boolean to Number conversion


Number("3.14") // returns 3.14
Number(" ")
// returns 0
Number("")
// returns 0
Number("99 88") // returns NaN
Number(false)
Number(true)

// 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>

//JavaScript Type Conversion Table

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

JavaScript Best Practices


//Java script Strict Mode
The "use strict" directive is new in JavaScript 1.8.5 (ECMAScript version 5). The
purpose of "use strict" is to indicate that the code should be executed in "strict
mode". With strict mode, you can not, for example, use undeclared variables. Strict
mode is declared by adding "use strict"; to the beginning of a script or a function.
"use strict";
x = 3.14;

// This will cause an error (x is not defined)

Strict mode makes it easier to write "secure" JavaScript.


Strict mode changes previously accepted "bad syntax" into real errors. As an
example, in normal JavaScript, mistyping a variable name creates a new global
variable. In strict mode, this will throw an error, making it impossible to accidentally
create a global variable. In normal JavaScript, a developer will not receive any error
feedback assigning values to non-writable properties. In strict mode, any
assignment to a non-writable property, a getter-only property, a non-existing
property, a non-existing variable, or a non-existing object, will throw an error. The
"use strict" directive is only recognized at the beginning of a script or a function.
//Style guidelines

camelCase for identifier names


Spaces around operators
Code indentation (4 spaces, do not use tabs different editors interpet tabs
differently)
Always end a simple statement with a semicolon
Variable and function names written as camelCase
Global variables written in UPPERCASE
Constants UPPERCASE
Symple syntax for external scrypts <script src="myscript.js"></script>
File names should be lower case

//BEST PRACTICES

Izbjegavati globalne varijable, izbjegavati new, avoid ==, avoid eval()


Minimize the use of global variables
All variables used in a function should be declared as local variables. Local
variables must be declared with the var keyword, otherwise they will become
global variables (Strict mode doesnt allow undeclared variables)

Declarations on top of each script or function (By default, JavaScript moves


all declarations to the top (JavaScript hoisting))
Initialize variables (It is a good coding practice to initialize variables when
you declare them)
Never declare Number, String, or Boolean Objects (Always treat
numbers, strings, or booleans as primitive values. Not as objects. Declaring
these types as objects, slows down execution speed, and produces nasty side
effects)

var x = "John";
var y = new String("John");
(x === y) // is false because x is a string and y is an object

Dont use new Object()

var
var
var
var
var
var
var

x1
x2
x3
x4
x5
x6
x7

Use === Comparison

Use Parameter Defaults (If a function is called with a missing argument,

=
=
=
=
=
=
=

{};
// 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;
}
}

End your switches with default

Avoid using eval()

//Test if object exists


if (typeof myObj !== "undefined" && myObj !== null)

//JAVASCRIPT PERFORMANCE
Reduce activity in loops

Reduce DOM Access


Accessing the HTML DOM is very slow, compared to other JavaScript statements. If
you expect to access a DOM element several times, access it once, and use it as a
local variable:
obj = document.getElementById("demo");
obj.innerHTML = "Hello";

Reduce DOM Size


Avoid Unnecessary Variables
Delay JavaScript Loading
Putting your scripts at the bottom of the page body, lets the browser load the page
first. While a script is downloading, the browser will not start any other downloads.
In addition all parsing and rendering activity might be blocked.
<script>
window.onload = downScripts;
function downScripts() {
var element = document.createElement("script");
element.src = "myScript.js";
document.body.appendChild(element);
}
</script>

//HTML EVENT HANDLERS

//JavaScript Objects, Properties, and Methods

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.

Data is in name/value pairs


Data is separated by commas
Curly braces hold objects
Square brackets hold arrays

//JSON Objects
{"firstName":"John", "lastName":"Doe"}

//Converting a JSON Text to a JavaScript Object


A common use of JSON is to read data from a web server, and display the data in a
web page.
var text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';
var obj = JSON.parse(text);

//JSON HTTP REQUEST

<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;

/w3schools/i is a regular expression. w3schools is a pattern (to be used in a


search). i is a modifier (modifies the search to be case-insensitive).
In JavaScript, regular expressions are often used with the two string methods:
search() and replace().
var str = "Visit W3Schools";
var n = str.search(/w3schools/i);
var str = "Visit Microsoft!";
var res = str.replace(/microsoft/i, "W3Schools");

In JavaScript, the RegExp object is a regular expression object with predefined


properties and methods. The test() method is a RegExp expression method. It
searches a string for a pattern, and returns true or false, depending on the result.
The following example searches a string for the character "e":
var patt = /e/;
patt.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

JAVASCRIPT W3SCHOOLS REFERENCE

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.

AJAX is based on internet standards, and uses a combination of:

XMLHttpRequest object (to retrieve data from a web server)


JavaScript/DOM (to display/use the data)

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

A cached file is not an option (update a file or database on the server).


Sending a large amount of data to the server (POST has no size limitations).
Sending user input (which can contain unknown characters), POST is more
robust and secure than GET.

xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);


xhttp.send();
xhttp.open("POST", "demo_post.asp", true);
xhttp.send();

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");

The url parameter of the open() method, is an address to a file on a server:


The file can be any kind of file, like .txt and .xml, or server scripting files like .asp
and .php (which can perform actions on the server before sending the response
back).
When using async=true, specify a function to execute when the response is ready in
the onreadystatechange event:
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();

//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();
}

A callback function is a function passed as a parameter to another function. If you


have more than one AJAX task on your website, you should create ONE standard
function for creating the XMLHttpRequest object, and call this for each AJAX task.
The function call should contain the URL and what to do on onreadystatechange
(which is probably different for each call):
function loadDoc(url, cfunc) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
cfunc(xhttp);
}
};
xhttp.open("GET", url, 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

You might also like