2. Why Study JavaScript?
• JavaScript is one of the 3 languages all web developers must learn:
• 1. HTML to define the content of web pages
• 2. CSS to specify the layout of web pages
• 3. JavaScript to program the behavior of web pages
3. JavaScript Display Possibilities
• JavaScript can "display" data in different ways:
• Writing into an HTML element, using innerHTML.
• Writing into the HTML output using document.write().
• Writing into an alert box, using window.alert().
• Writing into the browser console, using console.log().
4. JavaScript Keywords
• Break
• Continue
• Debugger
• Do..while
• For
• function
• If ….else
• Return
• Switch
• Try…..catch
• var
5. JavaScript Values
• The JavaScript syntax defines two types of values: Fixed values and
variable values.
• Fixed values are called literals.
• Example: 10.50, “Johan Doe”
• Variable values are called variables.
• Example: var x = 6;
6. JavaScript Comments
• JavaScript comments can be used to explain JavaScript code, and to
make it more readable.
• Single Line Comments
• Single line comments start with //.
• Multi-line Comments
• Multi-line comments start with /* and end with */.
8. JavaScript Type Operators
Operator Description
typeof Returns the type of a variable
instanceof Returns true if an object is an instance of an object
type
10. JavaScript Functions
• A JavaScript function is a block of code designed to perform a
particular task.
• Example:
• function myFunction(p1, p2) {
return p1 * p2;
}
11. JavaScript Objects
• You have already learned that JavaScript variables are containers for
data values.
• Objects are variables too. But objects can contain many values.
• var car = {type:"Fiat", model:"500", color:"white"};
13. JavaScript Events
• An HTML event can be something the browser does, or something a
user does.
• Here are some examples of HTML events:
• An HTML web page has finished loading
• An HTML input field was changed
• An HTML button was clicked
• <element event='some JavaScript'>
15. JavaScript Arrays
• JavaScript arrays are used to store multiple values in a single variable.
• Example:
• var cars = ["Saab", "Volvo", "BMW"];
16. Popping and Pushing
• The pop() method removes the last element from an array:
• var fruits = ["Banana", "Orange", "Apple", "Mango"];
• fruits.pop();
• The push() method adds a new element to an array (at the end):
• var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
17. JavaScript Errors - Throw and Try to Catch
• The try statement lets you test a block of code for errors.
• The catch statement lets you handle the error.
• The throw statement lets you create custom errors.
• The finally statement lets you execute code, after try and catch,
regardless of the result.
21. JavaScript Form Validation
• HTML form validation can be done by JavaScript.
• Server side validation is performed by a web server, after input has
been sent to the server.
• Client side validation is performed by a web browser, before input is
sent to a web server.
22. JavaScript Object Properties
• The syntax for accessing the property
of an object is:
• objectName.property // person.age
• or
• objectName["property"] // person["age"]
• Show data form Object:
• for (variable in object) {
code to be executed
}
23. Accessing Object Methods
• JavaScript methods are the actions that can be performed on objects.
• Example:
• var person = {
• firstName: "John",
• fullName : function() {
• return this.firstName;
• }
• };
• You access an object method with the following syntax:
• objectName.methodName()
24. JavaScript Object Constructors
• function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");
25. JavaScript Object Prototypes
• Every JavaScript object has a prototype. The prototype is also an
object.
• All JavaScript objects inherit their properties and methods from their
prototype.
26. JS Functions
• Function Definitions
• Function Parameters
• Function Invocation
• Function Call
• Function Apply
27. JavaScript HTML DOM Document
Method Description
document.getElementById(id) Find an element by element id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(name) Find elements by class name
Finding HTML Elements
28. Changing HTML Elements
Method Description
element.innerHTML = new html content Change the inner HTML of an element
element.attribute = new value Change the attribute value of an HTML element
element.setAttribute(attribute, value) Change the attribute value of an HTML element
element.style.property = new style Change the style of an HTML element
29. Adding and Deleting Elements
Method Description
document.createElement(element) Create an HTML element
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element
document.replaceChild(element) Replace an HTML element
document.write(text) Write into the HTML output stream
30. Changing HTML Style
• To change the style of an HTML element, use this syntax:
• document.getElementById(id).style.property = new style
31. HTML DOM Events
• HTML DOM events allow JavaScript to register different event
handlers on elements in an HTML document.
• References:
• https://www.w3schools.com/jsref/dom_obj_event.asp
32. The addEventListener() method
• The addEventListener() method attaches an event handler to the
specified element.
• Syntax:
• element.addEventListener(event, function, useCapture);
33. JavaScript Window
• Two properties can be used to determine the size of the browser window.
• Both properties return the sizes in pixels:
• window.innerHeight - the inner height of the browser window (in pixels)
• window.innerWidth - the inner width of the browser window (in pixels)
• Some other methods:
• window.open() - open a new window
• window.close() - close the current window
• window.moveTo() -move the current window
• window.resizeTo() -resize the current window
34. Window Screen
• The window.screen object can be written without the window prefix.
• screen.width
• screen.height
• screen.availWidth
• screen.availHeight
• screen.colorDepth
• screen.pixelDepth
35. JavaScript Window Location
• Window location can redirect any page
• Example:
• document.getElementById("demo").innerHTML =
"Page path is " + window.location.pathname;
36. JavaScript Timing Events
• The two key methods to use with JavaScript are:
• setTimeout(function, milliseconds)
Executes a function, after waiting a specified number of milliseconds.
• setInterval(function, milliseconds)
Same as setTimeout(), but repeats the execution of the function
continuously.
37. What is AJAX?
• AJAX = Asynchronous JavaScript And XML.
• AJAX is not a programming language.
• AJAX just uses a combination of:
A browser built-in XMLHttpRequest object (to request data from a web server)
JavaScript and HTML DOM (to display or use the data)
38. AJAX - The XMLHttpRequest Object
• All modern browsers support the XMLHttpRequest object.
• Systax:
• variable = new XMLHttpRequest();
39. AJAX - Send a Request To a Server
• The XMLHttpRequest object is used to exchange data with a server.
• xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
Method Description
open(method, url, async) Specifies the type of request
method: the type of request: GET or POST
url: the server (file) location
async: true (asynchronous) or false (synchronous)
send() Sends the request to the server (used for GET)
send(string) Sends the request to the server (used for POST)
40. GET or POST?
• 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.
41. AJAX - Server Response
Property Description
onreadystatechange Defines a function to be called when the readyState property changes
readyState Holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
status 200: "OK"
403: "Forbidden"
404: "Page not found"
For a complete list go to the Http Messages Reference
statusText Returns the status-text (e.g. "OK" or "Not Found")
42. jQuery
• jQuery is a JavaScript Library.
• jQuery greatly simplifies JavaScript programming.
• jQuery is easy to learn.
43. jQuery Selectors
• jQuery selectors are one of the most important parts of the jQuery
library.
• Example:
• Element Name/Tag Name
• Id
• Class
44. jQuery Effects - Hide and Show
• Example:
• $(selector).hide(speed,callback);
$(selector).show(speed,callback);
45. jQuery Effects - Fading
• With jQuery you can fade elements in and out of visibility.
• $(selector).fadeIn(speed,callback);
• $(selector).fadeOut(speed,callback);
• $(selector).fadeToggle(speed,callback);
• $(selector).fadeTo(speed,opacity,callback);
46. jQuery Effects - Sliding
• jQuery has the following slide methods:
• slideDown()
• slideUp()
• slideToggle()
47. jQuery - Get Content and Attributes
• Three simple, but useful, jQuery methods for DOM manipulation are:
text() - Sets or returns the text content of selected elements
html() - Sets or returns the content of selected elements (including
HTML markup)
val() - Sets or returns the value of form fields
48. jQuery - Remove Elements
• To remove elements and content, there are mainly two jQuery
methods:
• remove() - Removes the selected element (and its child elements)
• empty() - Removes the child elements from the selected element
49. jQuery - Get and Set CSS Classes
• jQuery has several methods for CSS manipulation. We will look at the
following methods:
• addClass() - Adds one or more classes to the selected elements
• removeClass() - Removes one or more classes from the selected elements
• toggleClass() - Toggles between adding/removing classes from the selected
elements
• css() - Sets or returns the style attribute