JavaScript & jQuery Creating Dynamic Webpages. About jQuery “Write less, do more.” MIT License...

Post on 17-Jan-2016

215 views 0 download

Transcript of JavaScript & jQuery Creating Dynamic Webpages. About jQuery “Write less, do more.” MIT License...

JavaScript & jQueryCreating Dynamic Webpages

About jQuery

•“Write less, do more.”•MIT License•Great cross-platform support (1.x more widely supported

than 2.x)

Browser Support•jQuery

•jQuery UI

Interacting with the PageSelectors and Accessors

The jQuery syntax is made for selecting HTML elements and performing some action on the elements.

•Basic syntax is: $(selector).action()▫A $ sign to define/access jQuery▫A (selector) to "query (or find)" HTML elements▫A jQuery action() to be performed on the element(s)

Selectors

•Selectors are used to tell JavaScript & jQuery which element(s) you are interested in working with

•Selectors follow the same pattern for jQuery as for CSS

Examples:

•$(this).hide() - hides the current element•$("p").hide() - hides all <p> elements•$(".test").hide() - hides all elements with class=“test”•$("#test").hide() - hides the element with id=“test”

What Can jQuery do For You?JavaScript JQuery

• Cumbersome syntax• Returns DOM objects

• Minimal code required• Returns jQuery object (wraps DOM

and adds functionality & convenience)

JS vs jQuery

JavaScript jQuery

//Returns the body div document.getElementById("body");

//Returns both divs (both participate in the "interactive" class) document.getElementsByClassName("interactive");

//Returns the body div

$("#body");

//Returns both divs (both participate in the "interactive" class)

$(".interactive");

<div class="interactive" id="body">Body Content</div>

<div class="interactive" id="footer">Footer Content</div>

#body.interactive

#footer.interactive

JavaScript Selection Methods• document.getElementById("myID");.

• document.getElementsByClassName("myName");

• document.getElementsByName("myName");

• document.getElementsByTagName("div");

• document.querySelector(“#id");

• document.querySelectorAll(“.class");

jQuery Selection Methods• $("Any pattern and/or combination of selectors you feel like");

• http://www.w3schools.com/jquery/jquery_ref_selectors.asp

AccessorsJavaScript jQuery

• Get an object’s HTMLvar html = document.getElementById(“myElement”).innerHTML; • Set an object’s HTMLdocument.getElementById(“#myElement”).innerHTML = “<span> Display this HTML </span>"; • Get an object’s valuevar text = document.getElementById(“myElement”).value;• Set an object’s valuedocument.getElementById(“myElement”).value = "Display this string";

• Get an object’s HTMLvar html = $(“#myElement”).html(); • Set an object’s HTML$(“#myElement”).html(“<span> Display this HTML</span>"); • Get an object’s textvar text = $(“#myElement”).text();• Set an object’s text$(“#myElement”).text("Display this string");• Get an object’s valuevar value = $(“#myElement”).val();• Set an object’s value$(“#myElement”).val("Display this string");

$().text();

From jQuery Documentation @ http://www.jQuery.com/

Document Ready Event

•$(document).ready(function(){

   // jQuery methods go here...

});

Example:

•$(document).ready(function(){    $("button").on(“click”,function(){        $("p").hide();    });});

•Mouse events - .click, .dblclick, .mouseenter, …..

•Keyboard Events - .keypress, .keydown…….

<!DOCTYPE html><html>

<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script>

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

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

});</script>

</head><body>

<h2>This is a heading</h2><p>This is a paragraph.</p><p>This is another paragraph.</p><button>Click me</button>

</body></html>

jQuery prototypingAll objects have a prototype property. It is simply an object from which other objects can inherit properties.

Example• function Person(name) {

this.name = name; } Person.prototype.sayHello = function () {

alert(this.name + " says hello"); }; var james = new Person("James");james.sayHello(); // Alerts "James says hello“

Explanation of Example• In this example, Person is a constructor function. It can

be instantiated by calling it with the new operator. Inside the constructor, the this keyword refers to the instance, so every instance has its own name property.

• The prototype of Person is shared between all instances. So all instances of Person have a sayHello method that they inherit from Person.prototype. By defining the sayHello method as a property of Person.prototype we are saving memory. We could just as easily give every instance of Person its own copy of the method (by assigning it to this.sayHello inside the constructor), but that's not as efficient.

Method chaining• Method returns an object, allowing the calls to be chained together in a

single statement without requiring variables to store the intermediate results

• jQuery relies heavily on chaining. This makes it easy to call several methods on the same selection

Java

Public class DiaLog{public DiaLog setTitle(String title){

//logic set titlereturn this;

}public DiaLog setMessage(String msg){

//logic set msgreturn this;

}}new Dialog().setTitle(“Title”).setMessage(“message”)

jQuery

$(document).ready(function() {

$(“li”).css(“color”,”blue”).slideUp(1000).slideDown(1000).attr(“title”,”my title”);

});

AJAXAsynchronous JavaScript and xml

What's AJAX?

•Group of web development techniques on the client side that enable the update of parts of page dynamically rather than requesting a whole page every time an event is triggered.

•Asynchronous means that your page can update any part without having to send an entire request for the whole page.

•JavaScript does the heavy lifting (handling events, server request and updating the page).

• uses XHR API for client server communication. •It’s called AJAX, but the input format can be text, html,

or json.

Why use AJAX

•More efficient way to transfer data.•Less time spent on updating.•Better user experience.•Page is more dynamic and responsive.

Example <!DOCTYPE html><html><head><script>function loadXMLDoc(url){var xmlhttp = new XMLHttpRequest();xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById('A1').innerHTML=xmlhttp.status; document.getElementById('A2').innerHTML=xmlhttp.statusText; document.getElementById('A3').innerHTML=xmlhttp.responseText; } }xmlhttp.open("GET",url,true);xmlhttp.send();}</script></head>

<body>

<h2>Retrieve data from XML file</h2><p><b>Status:</b><span id="A1"></span></p><p><b>Status text:</b><span id="A2"></span></p><p><b>Response:</b><span id="A3"></span></p><button onclick="loadXMLDoc('note.xml')">Get XML data</button>

</body></html>

JSON ObjectsA Brief Glossing

What is a JSON Object?

•A JSON object is an associative array (map/dictionary) that is machine and (arguably) human readable

•Commonly contains nested arrays/objects

What Does it Look Like?

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