frontend 27 jquery intro

25
Errors JavaScript Test a block of code for errors. Handle the error. Create custom errors. Execute code, after try and catch, regardless of the result. try catch throw finally Different errors can occur in JS. Errors can be coding errors made by the programmer, errors due to wrong input, and other unforeseeable things.

Upload: merab-tavartkiladze

Post on 16-Feb-2018

224 views

Category:

Documents


0 download

TRANSCRIPT

7/23/2019 FrontEnd 27 JQuery Intro

http://slidepdf.com/reader/full/frontend-27-jquery-intro 1/25

ErrorsJavaScript

Test a block of code forerrors.

Handle the error. Create custom errors.Execute co

and catch, the

try catch throw fin

Different errors can occur in JS.Errors can be coding errors made by the programmer, errors due to wrong input, and

unforeseeable things.

7/23/2019 FrontEnd 27 JQuery Intro

http://slidepdf.com/reader/full/frontend-27-jquery-intro 2/25

Errors: Try and CatchJavaScript

The try statement allows you todefine a block of code to betested for errors while it is beingexecuted.

Code

try {

adddlert("Welcome guest!");

}catch(err) {

console.log(err.message);

}The catch statement allows youto define a block of code to beexecuted, if an error occurs inthe try block.

7/23/2019 FrontEnd 27 JQuery Intro

http://slidepdf.com/reader/full/frontend-27-jquery-intro 3/25

Errors: ThrowJavaScript

When an error occurs, JS willstop and generate an errormessage.

In other words: JS will throw anerror. Code

throw "Too big"; // throw a textthrow 500; // throw a number

The throw statement allows youto create a custom error.

The exception can be a JSString, a Number, a Boolean oran Object.

7/23/2019 FrontEnd 27 JQuery Intro

http://slidepdf.com/reader/full/frontend-27-jquery-intro 4/25

Errors: Validation exampleJavaScript

If the value is wrong, anexception (err) is thrown.

The exception (err) is caught bythe catch statement and acustom error message isdisplayed.

Code

function myFunction() {

var message, x;

 message = document.getElementById("message")

 message.innerHTML = "";

x = document.getElementById("demo").value;

try {

x = Number(x);

if(x == "") throw "empty";

if(isNaN(x)) throw "not a number";

if(x > 10) throw "too high";

if(x < 5) throw "too low";

}

catch(err) {

 message.innerHTML = "Input is " +

}

}

7/23/2019 FrontEnd 27 JQuery Intro

http://slidepdf.com/reader/full/frontend-27-jquery-intro 5/25

Errors: FinallyJavaScript

The finally statement lets youexecute code, after try andcatch, regardless of the result.

Code

try {

Block of code to try

}

catch(err) {Block of code to handle errors

}

finally {

Code to be executed regardless of the try / catch re

}

7/23/2019 FrontEnd 27 JQuery Intro

http://slidepdf.com/reader/full/frontend-27-jquery-intro 6/25

Errors: FinallyJavaScript

Explain this.

Code

function myFunction() {

var message, x;

 message = document.getElementById("message")

 message.innerHTML = "";

x = document.getElementById("demo").value;

try {

x = Number(x);

if(x == "") throw "is empty";

if(isNaN(x)) throw "is not a number";

if(x > 10) throw "is too high";

if(x < 5) throw "is too low";

}

catch(err) {

 message.innerHTML = "Error: " + err + ".";

}

finally {

document.getElementById("demo").value = "

}

}

7/23/2019 FrontEnd 27 JQuery Intro

http://slidepdf.com/reader/full/frontend-27-jquery-intro 7/25

Errors: Debugger JavaScript

Debugger stops the execution ofJS, and calls the debuggingfunction.

If no debugging is available, the

debugger statement has noeffect.

With the debugger turned on,this code will stop executingbefore it executes the third line.

Code

var x = 15 * 5;

debugger;

document.getElementbyId("demo").innerHTML = x;

Result

7/23/2019 FrontEnd 27 JQuery Intro

http://slidepdf.com/reader/full/frontend-27-jquery-intro 8/25

JSONJavaScript

JSON is a format for storing and

transporting data.

JSON is often used when data

is sent from a server to a web

page.

● JSON is JavaScript Object Notation

● JSON is lightweight data interchange format

● JSON is language independent

● JSON is easy to understand

{"employees":[

{"firstName":"John", "lastName":"Doe"},

{"firstName":"Anna", "lastName":"Smith"},

{"firstName":"Peter", "lastName":"Jones"}

]}

Code

7/23/2019 FrontEnd 27 JQuery Intro

http://slidepdf.com/reader/full/frontend-27-jquery-intro 9/25

JSON RulesJavaScript

JSON arrays are written inside

square brackets.

Just like in JavaScript, an arraycan contain objects.

Data is in name/value pairs

Data is separated by commas

Curly braces hold objects

Square brackets hold arrays

"employees":[

{"firstName":"John", "lastName":"Doe"},

{"firstName":"Anna", "lastName":"Smith"},

{"firstName":"Peter", "lastName":"Jones"}

]

Code

7/23/2019 FrontEnd 27 JQuery Intro

http://slidepdf.com/reader/full/frontend-27-jquery-intro 10/25

Convert JSON to JS ObjectJavaScript

You can easily convert JSON toObject with JSON.parse()function.

var text = '{ "employees" : [' +

'{ "firstName":"John" , "lastName":"Doe" },' +

'{ "firstName":"Anna" , "lastName":"Smith" },' +

'{ "firstName":"Peter" , "lastName":"Jones" } ]}';

Create a JS string containing JSON syntax:

var obj = JSON.parse(text);

Use JSON.parse() to convert the string into a JavaScript object:

7/23/2019 FrontEnd 27 JQuery Intro

http://slidepdf.com/reader/full/frontend-27-jquery-intro 11/25

 jQuery Intro jQuery

 jQuery is a JS Library

$(document).ready(function(){

$("p").click(function(){

$(this).hide();

});

});

Example

 jQuery greatlysimplifies JSprogramming

 jQuery is elearn

7/23/2019 FrontEnd 27 JQuery Intro

http://slidepdf.com/reader/full/frontend-27-jquery-intro 12/25

Start working with jQuery

Download and connect thelibrary to head section.

 <head> 

 <script src="jquery-1.11.2.min.js"></script> 

 </head> 

Example

 jQuery

Or use CDN for it.  <script

src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/

.js"></script> 

Example

7/23/2019 FrontEnd 27 JQuery Intro

http://slidepdf.com/reader/full/frontend-27-jquery-intro 13/25

Syntax

In jQuery you select (query)HTML elements and perform

"actions" on them.

 jQuery

Define/access jQuery

Basic syntax

Query (or find) HTMLelements

To do sothe selec

$ (selector    )   ac

$(‘#demo’).hide();

7/23/2019 FrontEnd 27 JQuery Intro

http://slidepdf.com/reader/full/frontend-27-jquery-intro 14/25

Syntax

Please explain, whatelements will be hidden.

 jQuery

$(this).hide();

$("p").hide();

$(".test").hide();

$("#test").hide();

Example

7/23/2019 FrontEnd 27 JQuery Intro

http://slidepdf.com/reader/full/frontend-27-jquery-intro 15/25

Document.ready

This code is used to prevent any jQuery code from running beforethe document is finished loading(is ready).

It is good practice to wait for the

document to be fully loaded andready before working with it.

This also allows you to haveyour JS code before the body ofyour document, in the headsection.

 jQuery

$(document).ready(function(){

// code goes here...

});

Code

$(function(){

// jQuery methods go here...

});

Code

Or use a shorter definition for document.ready

7/23/2019 FrontEnd 27 JQuery Intro

http://slidepdf.com/reader/full/frontend-27-jquery-intro 16/25

Selectors

 jQuery selectors are based onCSS selectors and have almostthe same syntax.

 jQuery

// id selector

$("#test");

// class selector$(".test");

// tag selector

$("p");

Code

You can use class, tag or idselectors.

S l t

7/23/2019 FrontEnd 27 JQuery Intro

http://slidepdf.com/reader/full/frontend-27-jquery-intro 17/25

Selectors jQuery

Syntax Description

$("*") Selects all elements

$(this) Selects the current HTML element

$("p.intro") Selects all <p> elements with class="intro"

$("p:first") Selects the first <p> element

$("ul li:first") Selects the first <li> element of the first <ul>

$("ul li:first-child") Selects the first <li> element of every <ul>

$("[href]") Selects all elements with an href attribute

$(":button") Selects all <button> elements and <input> elements of type="button"

$("tr:even") Selects all even <tr> elements

$("tr:odd") Selects all odd <tr> elements

7/23/2019 FrontEnd 27 JQuery Intro

http://slidepdf.com/reader/full/frontend-27-jquery-intro 18/25

Events jQuery

 All the different visitor's actions that a web page canrespond to are called events.

Mouse Events Keyboard Events Form Events Document/Window Ev

click keypress submit load

dblclick keydown change resize

mouseenter keyup focus scroll

mouseleave blur unload

 An event represents the precise moment whenhappens.

7/23/2019 FrontEnd 27 JQuery Intro

http://slidepdf.com/reader/full/frontend-27-jquery-intro 19/25

Syntax for events

To assign a click event to allparagraphs on a page, you cando this:

 jQuery

$("p").click();

Code

The next step is to define whatshould happen when the event

fires. You must pass a functionto the event:

$("p").click(function(){

// action

});

Code

The dblclick() method attachesan event handler function to anHTML element.

$("p").dblclick(function(){

$(this).hide();

});

Code

7/23/2019 FrontEnd 27 JQuery Intro

http://slidepdf.com/reader/full/frontend-27-jquery-intro 20/25

Events

The mouseenter() methodattaches an event handlerfunction to an HTML element.

 jQuery

$("#p1").mouseenter(function(){

alert("You entered p1");

});

Code

The mouseleave() methodattaches an event handlerfunction to an HTML element.

$("#p1").mouseleave(function(){

alert("You leave p1");});

Code

The mousedown() methodattaches an event handlerfunction to an HTML element.

$("#p1").mousedown(function(){

alert("Mouse down over p1");

});

Code

7/23/2019 FrontEnd 27 JQuery Intro

http://slidepdf.com/reader/full/frontend-27-jquery-intro 21/25

Events

The mouseup() methodattaches an event handlerfunction to an HTML element.

 jQuery

$("#p1").mouseup(function(){

alert("Mouse up over p1!");

});

Code

The hover() method takes twofunctions and is a combination

of the mouseenter() andmouseleave() methods.

The first function is executedwhen the mouse enters theHTML element, and the secondfunction is executed when themouse leaves the HTMLelement:

$("#p1").hover(function(){

alert("You entered p1!");

},

function(){

alert("You now leave p1!");

});

Code

7/23/2019 FrontEnd 27 JQuery Intro

http://slidepdf.com/reader/full/frontend-27-jquery-intro 22/25

Events

The focus() method attaches anevent handler function to anHTML form field (gets focus).

 jQuery

$("input").focus(function(){

$(this).css("background-color", "#cccccc");

});

Code

The blur() method attaches anevent handler function to anHTML form field (loses focus).

$("input").blur(function(){

$(this).css("background-color", "#ffffff");

});

Code

7/23/2019 FrontEnd 27 JQuery Intro

http://slidepdf.com/reader/full/frontend-27-jquery-intro 23/25

hide() and show()

With jQuery, you can hide andshow HTML elements with thehide() and show() methods:

 jQuery

$("#hide").click(function(){

$("p").hide();

});

$("#show").click(function(){

$("p").show();

});

Code

The optional callback parameteris a function to be executed afterthe hide() or show() methodcompletes (you will learn moreabout callback functions in alater chapter).

$("button").click(function(){

$("p").hide(1000);

});

Code

7/23/2019 FrontEnd 27 JQuery Intro

http://slidepdf.com/reader/full/frontend-27-jquery-intro 24/25

toggle()

With jQuery, you can togglebetween the hide() and show()methods with the toggle()method.

Shown elements are hidden andhidden elements are shown

 jQuery

$("button").click(function(){

$("p").toggle();});

Code

Method Description

7/23/2019 FrontEnd 27 JQuery Intro

http://slidepdf.com/reader/full/frontend-27-jquery-intro 25/25

Method Description

animate() Runs a custom animation on the selectedelements

clearQueue() Removes all remaining queued functionsfrom the selected elements

delay() Sets a delay for all queued functions onthe selected elements

dequeue() Removes the next function from the queue,and then executes the function

fadeIn() Fades in the selected elements

fadeOut() Fades out the selected elements

fadeTo() Fades in/out the selected elements to agiven opacity

fadeToggle() Toggles between the fadeIn() andfadeOut() methods

Method Description

finish() Stops, removes and completeanimations for the selected ele

hide() Hides the selected elements

queue() Shows the queued functions oelements

show() Shows the selected elements

slideDown() Slides-down (shows) the selec

slideToggle() Toggles between the slideUp(slideDown() methods

slideUp() Slides-up (hides) the selected

stop() Stops the currently running anselected elements

toggle() Toggles between the hide() an

methods

Effects