Sie sind auf Seite 1von 25

JavaScript

Errors

Different errors can occur in JS.


Errors can be coding errors made by the programmer, errors due to wrong input, and other
unforeseeable things.

try

Test a block of code for


errors.

catch

Handle the error.

throw

finally

Create custom errors.

Execute code, after try


and catch, regardless of
the result.

JavaScript

The try statement allows you to


define a block of code to be
tested for errors while it is being
executed.

The catch statement allows you


to define a block of code to be
executed, if an error occurs in
the try block.

Errors: Try and Catch

Code

try {
adddlert("Welcome guest!");
}
catch(err) {
console.log(err.message);
}

JavaScript

Errors: Throw

When an error occurs, JS will


stop and generate an error
message.
In other words: JS will throw an
error.

The throw statement allows you


to create a custom error.
The exception can be a JS
String, a Number, a Boolean or
an Object.

Code

throw "Too big";


throw 500;

// throw a text
// throw a number

JavaScript

Errors: Validation example

Code
If the value is wrong, an
exception (err) is thrown.
The exception (err) is caught by
the catch statement and a
custom error message is
displayed.

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 " + err;
}
}

JavaScript

Errors: Finally

Code
The finally statement lets you
execute code, after try and
catch, regardless of the result.

try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
finally {
Code to be executed regardless of the try / catch result
}

JavaScript

Errors: Finally
Code

Explain this.

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 = "";
}
}

JavaScript

Debugger stops the execution of


JS, and calls the debugging
function.

If no debugging is available, the


debugger statement has no
effect.
With the debugger turned on,
this code will stop executing
before it executes the third line.

Errors: Debugger

Code

var x = 15 * 5;
debugger;
document.getElementbyId("demo").innerHTML = x;

Result

JSON

JavaScript

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

Code
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna",
"lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}

JavaScript

JSON Rules

Data is in name/value pairs


Data is separated by commas
Curly braces hold objects

Square brackets hold arrays


JSON arrays are written inside
square brackets.
Just like in JavaScript, an array
can contain objects.

Code
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]

JavaScript

Convert JSON to JS Object

Create a JS string containing JSON syntax:

You can easily convert JSON to


Object with JSON.parse()
function.

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


'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';

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


var obj = JSON.parse(text);

jQuery

jQuery is a JS Library

jQuery Intro

jQuery greatly
simplifies JS
programming

Example
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});

jQuery is easy to
learn

jQuery

Start working with jQuery

Example
Download and connect the
library to head section.

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

Example
Or use CDN for it.

<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min
.js"></script>

jQuery

Syntax

$(#demo).hide();
Basic syntax
In jQuery you select (query)
HTML elements and perform
"actions" on them.

(selector)

action()

Define/access jQuery

Query (or find) HTML


elements

To do something with
the selected element(s)

jQuery

Syntax

Example
$(this).hide();

Please explain, what


elements will be hidden.

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

jQuery

Document.ready

Code

This code is used to prevent any


jQuery code from running before
the document is finished loading
(is ready).

$(document).ready(function(){
// code goes here...
});

It is good practice to wait for the


document to be fully loaded and
ready before working with it.
This also allows you to have
your JS code before the body of
your document, in the head
section.

Or use a shorter definition for document.ready

Code

$(function(){
// jQuery methods go here...
});

jQuery

Selectors

Code
jQuery selectors are based on
CSS selectors and have almost
the same syntax.

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

You can use class, tag or id


selectors.

// tag selector
$("p");

jQuery

Selectors

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

Events

jQuery

Mouse Events

Keyboard Events

Form Events

Document/Window Events

click

keypress

submit

load

dblclick

keydown

change

resize

mouseenter

keyup

focus

scroll

blur

unload

mouseleave

All the different visitor's actions that a web page can


respond to are called events.

An event represents the precise moment when something


happens.

jQuery

Syntax for events


Code

To assign a click event to all


paragraphs on a page, you can
do this:

The next step is to define what


should happen when the event
fires. You must pass a function
to the event:

$("p").click();

Code
$("p").click(function(){
// action
});

Code
The dblclick() method attaches
an event handler function to an
HTML element.

$("p").dblclick(function(){
$(this).hide();
});

jQuery

Events
Code

The mouseenter() method


attaches an event handler
function to an HTML element.

$("#p1").mouseenter(function(){
alert("You entered p1");
});

Code
The mouseleave() method
attaches an event handler
function to an HTML element.

$("#p1").mouseleave(function(){
alert("You leave p1");
});

Code
The mousedown() method
attaches an event handler
function to an HTML element.

$("#p1").mousedown(function(){
alert("Mouse down over p1");
});

jQuery

Events
Code

The mouseup() method


attaches an event handler
function to an HTML element.

$("#p1").mouseup(function(){
alert("Mouse up over p1!");
});

Code

The hover() method takes two


functions and is a combination
of the mouseenter() and
mouseleave() methods.
The first function is executed
when the mouse enters the
HTML element, and the second
function is executed when the
mouse leaves the HTML
element:

$("#p1").hover(function(){
alert("You entered p1!");
},
function(){
alert("You now leave p1!");
});

jQuery

Events

Code

The focus() method attaches an


event handler function to an
HTML form field (gets focus).

$("input").focus(function(){
$(this).css("background-color", "#cccccc");
});

Code
The blur() method attaches an
event handler function to an
HTML form field (loses focus).

$("input").blur(function(){
$(this).css("background-color", "#ffffff");
});

jQuery

hide() and show()


Code

With jQuery, you can hide and


show HTML elements with the
hide() and show() methods:

$("#hide").click(function(){
$("p").hide();
});
$("#show").click(function(){
$("p").show();
});

Code
The optional callback parameter
is a function to be executed after
the hide() or show() method
completes (you will learn more
about callback functions in a
later chapter).

$("button").click(function(){
$("p").hide(1000);
});

jQuery

toggle()

Code
With jQuery, you can toggle
between the hide() and show()
methods with the toggle()
method.
Shown elements are hidden and
hidden elements are shown

$("button").click(function(){
$("p").toggle();
});

Method

Description

animate()

Runs a custom animation on the selected


elements
Method

Description

clearQueue()

Removes all remaining queued functions


from the selected elements

finish()

Stops, removes and completes all queued


animations for the selected elements

Sets a delay for all queued functions on


the selected elements

hide()

Hides the selected elements

queue()

Shows the queued functions on the selected


elements

show()

Shows the selected elements

slideDown()

Slides-down (shows) the selected elements

slideToggle()

Toggles between the slideUp() and


slideDown() methods

slideUp()

Slides-up (hides) the selected elements

stop()

Stops the currently running animation for the


selected elements

toggle()

Toggles between the hide() and show()


methods

delay()

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 a


given opacity

fadeToggle()

Toggles between the fadeIn() and


fadeOut() methods

Effects

Das könnte Ihnen auch gefallen