1 course notes for cs1520 programming languages part c by john c. ramirez / wonsun ahn department of...

26
1 Course Notes for Course Notes for CS1520 CS1520 Programming Languages Programming Languages Part C Part C By By John C. Ramirez / Wonsun Ahn John C. Ramirez / Wonsun Ahn Department of Computer Science Department of Computer Science University of Pittsburgh University of Pittsburgh

Upload: posy-ross

Post on 20-Jan-2016

223 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Course Notes for CS1520 Programming Languages Part C By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

1

Course Notes forCourse Notes for

CS1520 CS1520 Programming Programming

LanguagesLanguagesPart CPart C

ByByJohn C. Ramirez / Wonsun AhnJohn C. Ramirez / Wonsun Ahn

Department of Computer ScienceDepartment of Computer ScienceUniversity of PittsburghUniversity of Pittsburgh

Page 2: 1 Course Notes for CS1520 Programming Languages Part C By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

2

• These notes are intended for use by students in CS1520 at These notes are intended for use by students in CS1520 at the University of Pittsburgh and no one elsethe University of Pittsburgh and no one else

• These notes are provided free of charge and may not be sold These notes are provided free of charge and may not be sold in any shape or formin any shape or form

• Material from these notes is obtained from various sources, Material from these notes is obtained from various sources, including, but not limited to, the following:including, but not limited to, the following:

4 http://docs.jquery.com/Main_Page

4 http://www.w3schools.com/jquery/default.asp

4 http://jqfundamentals.com/

4 Programming the World Wide Web, multiple editions, by Robert Programming the World Wide Web, multiple editions, by Robert Sebesta (AW)Sebesta (AW)

Page 3: 1 Course Notes for CS1520 Programming Languages Part C By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

3

Lecture 1: Intro to JQueryLecture 1: Intro to JQuery

• What is What is JQueryJQuery??4 Not actually a language in and of itselfNot actually a language in and of itself

4 Rather, it is large library of Javascript Rather, it is large library of Javascript code designed to make access and code designed to make access and updates via DOM much simpler than updates via DOM much simpler than with straight Javascriptwith straight Javascript

4 Everything it does we could do without Everything it does we could do without it, but it does make a lot of what we do it, but it does make a lot of what we do easiereasier• You will use JQuery in Assignment 4You will use JQuery in Assignment 4

Page 4: 1 Course Notes for CS1520 Programming Languages Part C By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

4

Lecture 1: JQuery LibraryLecture 1: JQuery Library

• How to include / access JQuery?How to include / access JQuery?4 We can download the library locally and We can download the library locally and

include the fileinclude the file<script src = ”localJQuery.js"></script><script src = ”localJQuery.js"></script>

• Where localJQuery.js is our local copy of the Where localJQuery.js is our local copy of the librarylibrary

4 Alternatively, we can link to a version on the Alternatively, we can link to a version on the Web:Web:<script src = ”http://code.jquery.com/jquery-latest.js"><script src = ”http://code.jquery.com/jquery-latest.js">

</script></script>

• Keeps code up to dateKeeps code up to date

• Must be online to use this, howeverMust be online to use this, however

Page 5: 1 Course Notes for CS1520 Programming Languages Part C By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 1: JQuery InitializationLecture 1: JQuery Initialization

• JQuery depends on the DOM being JQuery depends on the DOM being ready for accessready for access4 We do not want to use it until the page We do not want to use it until the page

has been completely loadedhas been completely loaded

4 Once this has occurred we can use Once this has occurred we can use JQuery to access parts of our document JQuery to access parts of our document (in various ways) and to manipulate (in various ways) and to manipulate them (also in various ways)them (also in various ways)

5

Page 6: 1 Course Notes for CS1520 Programming Languages Part C By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 1: JQuery InitializtionLecture 1: JQuery Initializtion

• A good way to make sure the DOM is A good way to make sure the DOM is ready before using JQuery is to put our ready before using JQuery is to put our JQuery access statements into a JQuery access statements into a callback function: callback function:

<script><script>$(document).ready($(document).ready(function(){function(){// Code here will execute// Code here will execute// when the “ready” event occurs// when the “ready” event occurs

}});); </script></script>

• The callback function typically contains The callback function typically contains initialization codeinitialization code

– Registering event handlersRegistering event handlers– Performing initial modifications to the DOMPerforming initial modifications to the DOM

6

Page 7: 1 Course Notes for CS1520 Programming Languages Part C By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 1: JQuery InitializationLecture 1: JQuery Initialization

• Note the syntaxNote the syntax– $(document).ready(function(){ … });$(document).ready(function(){ … });– JQuery interactions are prefixed by $JQuery interactions are prefixed by $– $ is a function in the JQuery library that $ is a function in the JQuery library that

returns a JQuery object that represents the returns a JQuery object that represents the argumentargument

» In this case, the argument is the document itselfIn this case, the argument is the document itself

• Arguments can be:Arguments can be:– Existing DOM element objectsExisting DOM element objects– HTML code (allows creation of new DOM HTML code (allows creation of new DOM

elements)elements)– Most often are Most often are selectors selectors

• Selector: a “query” string that selects a Selector: a “query” string that selects a set of elements from the DOM treeset of elements from the DOM tree

– Much as we selected rows using queries in SQLMuch as we selected rows using queries in SQL

7

Page 8: 1 Course Notes for CS1520 Programming Languages Part C By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 1: SelectionLecture 1: Selection

4 Selectors allow operations on Selectors allow operations on setssets of of HTML elementsHTML elements• Adding event handlersAdding event handlers

• Adding / Modifying DOM nodesAdding / Modifying DOM nodes

4 Examples of selector strings:Examples of selector strings:• Selecting by Selecting by TAG nameTAG name::

$(“tagname”)$(“tagname”)–Returns an array of tags that match Returns an array of tags that match tagnametagname

• Selecting by Selecting by IDID::$(“#theid”)$(“#theid”)–Returns element with id equal to Returns element with id equal to theidtheid

8

Page 9: 1 Course Notes for CS1520 Programming Languages Part C By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 1: SelectionLecture 1: Selection

• Selection by Selection by CSSCSS class: class:$(“.className”)$(“.className”)–Returns an array of elements with Returns an array of elements with class class .className.className

• Selection by Selection by odd / evenodd / even::$(“element:odd”)$(“element:odd”)–Returns array of items matching element with Returns array of items matching element with odd odd index values (with indices starting at 0)index values (with indices starting at 0)

• Selection by Selection by index:index:$(“element:eq(2)”)$(“element:eq(2)”)$(“element:lt(4)”)$(“element:lt(4)”)$(“element:gt(1)”)$(“element:gt(1)”)–Returns elements specified by index (Returns elements specified by index (eq eq = = equal, equal, lt lt = less than, = less than, gtgt = greater than) = greater than)

• Plus MANY MANY MOREPlus MANY MANY MORE

9

Page 10: 1 Course Notes for CS1520 Programming Languages Part C By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 1: SelectionLecture 1: Selection

• We can even use selectors to find nested We can even use selectors to find nested elements in a very intuitive wayelements in a very intuitive way$(“outerElement innerElement”)$(“outerElement innerElement”)–This can be handy when we have several elements This can be handy when we have several elements of the same type but we want to only modify nested of the same type but we want to only modify nested elements within a certain oneelements within a certain one$(“element#id”)$(“element#id”)–This allows us to match a specific element with a This allows us to match a specific element with a specific idspecific id

• Let’s look at a simple exampleLet’s look at a simple example–See jqex1-nojq.html and jqex1.htmlSee jqex1-nojq.html and jqex1.html

• For more on selection see:For more on selection see:–http://www.w3schools.com/jquery/jquery_ref_selectors.asp

–http://api.jquery.com/category/selectors/

10

Page 11: 1 Course Notes for CS1520 Programming Languages Part C By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 1: Modifying ElementsLecture 1: Modifying Elements

4 In the first example, we already saw how In the first example, we already saw how we can modify selected elementswe can modify selected elements• Basically, once an element has been Basically, once an element has been

selected we can do whatever we want to itselected we can do whatever we want to it

• Some examples:Some examples:$(selector).css()$(selector).css()

» Update the CSS of the selected element(s)Update the CSS of the selected element(s)$(selector).append()$(selector).append()$(selector).addClass()$(selector).addClass()$(selector).attr()$(selector).attr()

……» Many DOM methods to update properties of the Many DOM methods to update properties of the

elementelement» See: See:

http://www.w3schools.com/jquery/jquery_ref_html.asp

11

Page 12: 1 Course Notes for CS1520 Programming Languages Part C By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 1: Modifying ElementsLecture 1: Modifying Elements

$(selector).hide()$(selector).hide()$(selector).show()$(selector).show()

… … »Methods to change appearance of elementsMethods to change appearance of elements»See: See: http://www.w3schools.com/jquery/jquery_ref_effects.asp

$(selector).bind()$(selector).bind()$(selector).click()$(selector).click()$(selector).focus()$(selector).focus()$(selector).mouseover()$(selector).mouseover()

……»Methods to deal with events and event handlingMethods to deal with events and event handling»See: See: http://www.w3schools.com/jquery/jquery_ref_events.asp http://www.w3schools.com/jquery/jquery_ref_events.asp

• We will look at some of these in more We will look at some of these in more detaildetail

–Others you will need to look up at your leisureOthers you will need to look up at your leisure

12

Page 13: 1 Course Notes for CS1520 Programming Languages Part C By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 1: Modifying ElementsLecture 1: Modifying Elements

4 Note: Just as in most situations, there is Note: Just as in most situations, there is often more than one way of doing often more than one way of doing things with JQuerythings with JQuery• Sometimes, one approach may be Sometimes, one approach may be

better than another, but in other better than another, but in other situations they are just differentsituations they are just different

• DonDon’’t assume the way I present t assume the way I present something is the only way to do itsomething is the only way to do it

– Or even necessarily the best way!Or even necessarily the best way!

13

Page 14: 1 Course Notes for CS1520 Programming Languages Part C By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 1: Modifying Elements Lecture 1: Modifying Elements

4 Problem:Problem: Iterating through the rows of Iterating through the rows of a table and adding a button to each a table and adding a button to each rowrow• We want a click of the button to toggle We want a click of the button to toggle

a class assignment to the rowa class assignment to the row

4 Solution:Solution:

1)1)First we need to figure out how to First we need to figure out how to iterate through the rowsiterate through the rows

2)2)We then must add a new button to We then must add a new button to each roweach row

3)3)We must then add a click event handler We must then add a click event handler to each new buttonto each new button

14

Page 15: 1 Course Notes for CS1520 Programming Languages Part C By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 1: Modifying ElementsLecture 1: Modifying Elements

1)1) JQuery has the each() iteratorJQuery has the each() iterator• It iterates through each matched element in It iterates through each matched element in

a selector, executing a callback function for a selector, executing a callback function for eacheach

– The callback function receives two arguments, The callback function receives two arguments, the current matched element and the current the current matched element and the current index (starting at 0)index (starting at 0)

• Note: The notion of iteration is common and Note: The notion of iteration is common and we have seen it already in Java and PHPwe have seen it already in Java and PHP

– The difference with this iterator is the way the The difference with this iterator is the way the code is executed – as a function call for each code is executed – as a function call for each element element

• Use a selector to get the rows of the table Use a selector to get the rows of the table and then use each() to access each one in and then use each() to access each one in turnturn

15

Page 16: 1 Course Notes for CS1520 Programming Languages Part C By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 1: Modifying ElementsLecture 1: Modifying Elements

2)2) We can use the append() functionWe can use the append() function• This allows us to add arbitrary text / html to This allows us to add arbitrary text / html to

an elementan element

• Add an input button to the current rowAdd an input button to the current row

3)3) There are a couple of ways we can do thisThere are a couple of ways we can do this• We can “hard code” the onclick attribute to We can “hard code” the onclick attribute to

a callback function that will toggle the classa callback function that will toggle the class

• Access the button using JQuery immediately Access the button using JQuery immediately after adding it and use the click() function to after adding it and use the click() function to assign the callback functionassign the callback function

4 See jqex2.html and jqex2b.htmlSee jqex2.html and jqex2b.html

16

Page 17: 1 Course Notes for CS1520 Programming Languages Part C By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 2: Modifying ElementsLecture 2: Modifying Elements

4 Problem:Problem: Adjusting the font size of our Adjusting the font size of our document as we increase or decrease document as we increase or decrease the window widththe window width

4 Solution:Solution:

1)1) We need to detect the width of the We need to detect the width of the documentdocument

2)2) We need to calculate a font size based We need to calculate a font size based on that widthon that width

3)3) We need to recognize a resize event We need to recognize a resize event and call a function to update the font and call a function to update the font sizesize

17

Page 18: 1 Course Notes for CS1520 Programming Languages Part C By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 2: Modifying ElementsLecture 2: Modifying Elements

1)1) We can use the width() function to find We can use the width() function to find out the width of the documentout the width of the document

2)2) There are several ways ways that we There are several ways ways that we can do thiscan do this• Depends on how we are actually storing / Depends on how we are actually storing /

keeping the fontkeeping the font

• CSS allows for many different font CSS allows for many different font metricsmetrics

– ptpt (points) (points)– pxpx (pixels) (pixels)– emem (ems) (ems)– %% (percent of the default size for the browser) (percent of the default size for the browser)

» For scaling it is probably better to use em or %For scaling it is probably better to use em or %» If you need a fixed size, you can use pt or pxIf you need a fixed size, you can use pt or px

18

Page 19: 1 Course Notes for CS1520 Programming Languages Part C By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 2: Modifying ElementsLecture 2: Modifying Elements

• See:See:– http://www.w3.org/Style/Examples/007/http://www.w3.org/Style/Examples/007/

units.en.htmlunits.en.html– http://kyleschaeffer.com/best-practices/css-font-http://kyleschaeffer.com/best-practices/css-font-

size-em-vs-px-vs-pt-vs/ size-em-vs-px-vs-pt-vs/

• In any case, we can calculate a new font In any case, we can calculate a new font size based on the relative width of the size based on the relative width of the resized window vs. that of the originalresized window vs. that of the original

3)3) JQuery has a resize() function that JQuery has a resize() function that takes a callback for the resize eventtakes a callback for the resize event• We simply put code into this function We simply put code into this function

that we want to execute each time the that we want to execute each time the window is resizedwindow is resized

4 See jqex3.html and jqex3b.htmlSee jqex3.html and jqex3b.html19

Page 20: 1 Course Notes for CS1520 Programming Languages Part C By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 2: Modifying ElementsLecture 2: Modifying Elements

• Problem:Problem: We want to show the user a We want to show the user a list of items and have him/her rank list of items and have him/her rank them by the order they are chosenthem by the order they are chosen4 They will then be placed into a new list They will then be placed into a new list

showing the rankingshowing the ranking

• Solution:Solution:

1)1)Iterate through list, attaching on click Iterate through list, attaching on click event handlerevent handler

2)2)Handler will remove list item from an Handler will remove list item from an unordered list and add it to an ordered unordered list and add it to an ordered listlist

20

Page 21: 1 Course Notes for CS1520 Programming Languages Part C By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 2: Modifying ElementsLecture 2: Modifying Elements

1)1) We can again use the each() function We can again use the each() function to iterate through all <li> elements in to iterate through all <li> elements in an unordered listan unordered list• To each we assign a callback function To each we assign a callback function

for the click() eventfor the click() event

• For a bit of added style we also use the For a bit of added style we also use the hover() function to update the style hover() function to update the style when the mouse is over the elementwhen the mouse is over the element

2)2) For the current <li> element, we For the current <li> element, we simply remove() it from the simply remove() it from the unordered list and append it to an unordered list and append it to an ordered list (<ol>)ordered list (<ol>)

21

Page 22: 1 Course Notes for CS1520 Programming Languages Part C By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 2: Modifying ElementsLecture 2: Modifying Elements

• We also handle some special cases:We also handle some special cases:– Initially there is NO ordered list, so for the Initially there is NO ordered list, so for the

first element selected we must create the first element selected we must create the <ol><ol>

– After all items have been moved, the old After all items have been moved, the old <ul> is empty, so we remove that<ul> is empty, so we remove that

4 See jqex4.htmlSee jqex4.html

22

Page 23: 1 Course Notes for CS1520 Programming Languages Part C By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 2: AJAXLecture 2: AJAX

• JQuery has a lot of AJAX convenience JQuery has a lot of AJAX convenience functionsfunctions

• See: http://api.jquery.com/category/ajax/ See: http://api.jquery.com/category/ajax/

4 They allow the full AJAX capabilitiesThey allow the full AJAX capabilities• As if you were using XMLHttpRequest As if you were using XMLHttpRequest

directlydirectly

4 They also allow some “shorthand” accessThey also allow some “shorthand” access

4 Let’s look at a few functionsLet’s look at a few functions• $.ajax()$.ajax()

– Most general ajax() functionMost general ajax() function– Has options to more or less do whatever you Has options to more or less do whatever you

wantwant» Headers, callbacks, cache, etcHeaders, callbacks, cache, etc

23

Page 24: 1 Course Notes for CS1520 Programming Languages Part C By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 2: AJAXLecture 2: AJAX

4 However, in many cases we use a However, in many cases we use a specific variation of an AJAX callspecific variation of an AJAX call

4 JQuery has some predefined variations JQuery has some predefined variations that are very convenientthat are very convenient• .load(url [,data] [,callback]).load(url [,data] [,callback])

– This is actually a function that is This is actually a function that is called from a called from a matched / selected elementmatched / selected element

– It makes an AJAX call to update the selected It makes an AJAX call to update the selected element’s data from a serverelement’s data from a server

– Ex:Ex:$(“#theTable tr”).load(‘url’);$(“#theTable tr”).load(‘url’);

» Will get the file from ‘url’ (which could be the Will get the file from ‘url’ (which could be the result of a script) and load it into the selected result of a script) and load it into the selected table rowtable row

» We can also put in a callback function but it is We can also put in a callback function but it is not requirednot required

24

Page 25: 1 Course Notes for CS1520 Programming Languages Part C By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 2: AJAXLecture 2: AJAX

• .get(url [,data] [,callback] [,datatype]).get(url [,data] [,callback] [,datatype]).post(url [,data] [,callback] [,datatype]).post(url [,data] [,callback] [,datatype])

– Make AJAX requests with the stated default Make AJAX requests with the stated default way of passing parametersway of passing parameters

– Both can supply options to the serverBoth can supply options to the server

• Many other functions are available to Many other functions are available to specific optionsspecific options

4 AJAX return datatype:AJAX return datatype:• Cool thing in JQuery:Cool thing in JQuery:

– Default is Intelligent GuessDefault is Intelligent Guess» JQuery looks at the header / format of the JQuery looks at the header / format of the

returned document and makes its judgment returned document and makes its judgment about the typeabout the type

» Automatically parses it based on that guessAutomatically parses it based on that guess

25

Page 26: 1 Course Notes for CS1520 Programming Languages Part C By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 2: AJAXLecture 2: AJAX

26