729G26 Interaction Programming Lecture 3

advertisement
729G26 Interaction
Programming
Lecture3
Lecture overview
⁃ jQuery- writeless,domore
⁃ Capturing eventsusing jQuery
⁃ Manipulating theDOM,attributesandcontentwith
jQuery
⁃ Animation withjQuery
⁃ Describing interaction
Todays lecture in the
context of the course
⁃ jQueryisthemostusedJavaScriptlibrary.Withityou
writeless,anddomore.
⁃ Tobeabletocommunicateyourinteractionideas,we
needsomekind oflanguage,e.g.wireframesand
transitiondiagrams
⁃ Nextweekwewilltalkabout creatingUIcomponents
using jQueryUI+howtousethird partycomponents.
“jQuery is a fast, small, and feature-rich
JavaScript library. It makes things like HTML
document traversal and manipulation, event
handling, animation, and Ajax much simpler with
an easy-to-use API that works across a multitude
of browsers.”
jQuery.com
“jQuery is a fast, small, and feature-rich
JavaScript library. It makes things like HTML
document traversal and manipulation, event
handling, animation, and Ajax much simpler with
an easy-to-use API that works across a multitude
of browsers.”
jQuery.com
“jQuery is a fast, small, and feature-rich
JavaScript library. It makes things like HTML
document traversal and manipulation, event
handling, animation, and Ajax much simpler with
an easy-to-use API that works across a multitude
of browsers.”
jQuery.com
“jQuery is a fast, small, and feature-rich
JavaScript library. It makes things like HTML
document traversal and manipulation, event
handling, animation, and Ajax much simpler with
an easy-to-use API that works across a multitude
of browsers.”
jQuery.com
“jQuery is a fast, small, and feature-rich
JavaScript library. It makes things like HTML
document traversal and manipulation, event
handling, animation, and Ajax much simpler with
an easy-to-use API that works across a multitude
of browsers.”
jQuery.com
“jQuery is a fast, small, and feature-rich
JavaScript library. It makes things like HTML
document traversal and manipulation, event
handling, animation, and Ajax much simpler with
an easy-to-use API that works across a multitude
of browsers.”
jQuery.com
“jQuery is a fast, small, and feature-rich
JavaScript library. It makes things like HTML
document traversal and manipulation, event
handling, animation, and Ajax much simpler with
an easy-to-use API that works across a multitude
of browsers.”
jQuery.com
⁃ January14,2006:JohnResig releasedthefirstversionof
jQueryBarCampNYC
⁃ August 26,2006:jQuery v1.0Released
⁃ April 18,2013:jQuery2.0Released
⁃ Jan24,2014:jQuery 2.1Released
⁃ April 28,2015:jQuery2.1.4/1.11.3Released
⁃ July13,2015:jQuery3.0Alpha/jQuery Compat 3.0Alpha
Semantic Versioning 2.0.0
⁃ Version numbering: MAJOR.MINOR.PATCH,
⁃ MAJOR :incompatible APIchanges
⁃ MINOR :addfunctionality inabackwards-compatible
manner
⁃ PATCH :backwards-compatiblebug fixes.
⁃ Seehttp://semver.org/
jQuery 1.11.x vs 2.1.x
⁃ jQuery1.9+and2.0+arethesamefornewerbrowsers.
⁃ 2.0+branchgetsridoftheextracodethatprovides
support forlegacybrowsers
⁃ ThemostusedJavaScriptlibraryonthewebtoday.Just
searchforjQueryinthepagesource.
⁃ W3TechTechnology Survey, Nov2015:jQueryuseon
97.5%oftheirtrackedwebdomainnames(around 67%of
allwebsites)
‒
http://w3techs.com/technologies/details/js-jquery/all/all
⁃ Examples
‒
dn.se
‒
microsoft.com
‒
wikipedia
Learn more about jQuery
http://learn.jquery.com/
jQuery topics for today
⁃ HTMLdocument traversal
⁃ Manipulating elements
⁃ Creatingelements
⁃ EventsinjQuery
⁃ Animation using jQuery
Setting up jQuery
⁃ Justlikelinking toafilecontaining yourJavaScript
⁃ LinktothejQuerylibrary,ordownload andlinktothe
jQuerylibrary.
⁃ Examplelinking:
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
Calling jQuery
⁃ jQuerydefines afunction called$ (whichisalsobound to
thesymboljQuery)
⁃ $===jQuery
⁃ The$ function isusedtoquerytheHTMLpageforasetof
jQueryobjects.
⁃ Wethen callmethods associatedwithjQuery objects.
jQuery script loader
$(document).ready(function() {
// your code here
});
// ordinary JavaScript
window.document.onload = function() {
// your code here
}
CODELA 1
https://www.ida.liu.se/codela/as/
Grabbing stuff
from the web
page
Retrieving elements using
jQuery
⁃ UseaCSSselector tohavejQueryfetcharesultset (a
specialjQuery array).
⁃ Theterms“matchedset”and“wrapperset”are
sometimesused insteadofresultset.
⁃ Theresultset,technicallycontainsDOMelements,each
wrappedinsideajQuery object.
⁃ ACSSselectorcanbecombined withafilter.
Examples
$("li")
//
$("a")
//
$(".thumbnail")
//
$("#container")
//
$("#menu .menuitem") //
//
//
fetch all the li elements
fetch all the a elements
fetch all element with class thumbnail
fetch the element with the id container.
fetch all the elements with the class
menuitem that are descendants of the
element with the id="menu".
List of CSS selectors
selector
resultset
*
allelements
TagName
allelements ofaspecifictype
.ClassName
allelements withaspecific class
#idName
allelements withaspecific id
TagA TagB
allelements oftypeTagBthataredescendedfromatagofType a
TagA > TagB
allelelemts oftypeTagBthataredirectchildrenofTagA
TagA+TagB
allelelemts thatarechildrenofTagA
TagA~TagB
allelements oftypeTagBthatareproceededbyanelement ofTabA
TagA:has(TagB)
allelements tagAthathasaTabBchildelement
TagA.Classname
allelelemts oftypeTagAsthatalsohavetheclassClassname.
TagA[attribute]
allelements oftypeTagAthathavetheattribute
TagA[attribute=value]
allelelemts oftypeTagAthathavetheattributewiththevaluevalue
TagA[attribute^=value]
allelements oftypeTagAthathavetheattributewithavaluethatstarts withvalue
TagA[attribute$=value]
allelements oftypeTagAthathavetheattributewithavaluethatends withvalue
TagA[attribute*=value]
allelements oftypeTagAthathavetheattributewithavaluethatcontains value
Example filters
selector
resultset
BaseSelector:first
firstelement ofresultset
BaseSelector:last
lastelement ofresultset
BaseSelector:even
allelements withaspecific class
BaseSelector:odd
allelements withaspecific id
BaseSelector:not(filterSelector)
select elements thatdonotmatchthefilterSelector
BaseSelector:contains(text)
select elements thatcontainthespecifiedtext
BaseSelector:hidden
select elements thatarehidden
BaseSelector:visible
select elements thatarevisible
Nice stuff
$("li").each()
$("a").find()
$("bla").get()
$("p").size()
Events in
jQuery
Pattern for handling
events in jQuery
// select an element, access an event handler and
// set the function used to handle the event
// åäö
// we can use a reference to a previously defined
function
$(selector:filter).eventName(functionName);
// or provide an anonymously defined function
$(selector:filter).eventName(function() {
// stuff to do
});
jQuery mouse event handlers
Eventhandler
Description
dblclick
doubleclick
mousedown
mousebuttonpresseddown
mouseup
mousebuttonreleased
mouseover
mouseisoveranelement
mouseout
mousemovesoutfromanelement
mousemove
themousemoves
jQuery document/window
events
Eventhandler
Description
load
whenthebrowserfinishesdownloading
allfiles:HTML,images,CSS,JavaScriptetc
unload
clickalinktoanotherpage,closeatab,
closewindow
scroll
dragthescrollbar,keyboardtoscroll,
mousescrollwheel
resize
e.g.clickingthemaximizebutton,dragging
theresizehandle
jQuery form events
Eventhandler
Description
submit
whenauserpressesthesubmitbutton
reset
whenauserpressestheformresetbutton
change
whenaformelement’svaluechanges
focus
whenaformelementreceivesfocus,e.g.
whenatextfieldbecomesactive
blur
whenaformelementloosesfocus
jQuery form events
Eventhandler
Description
keypress
whentheuserpressesdown akey,
continuestofirewhilethekeyisdown
keydown
whentheuserpressesdown akey,some
browserdonotfirecontinually,butsome
do
keyup
whentheuserreleasesthekey
Special jQuery events
Eventhandler
Description
hover
handlesboth mouseoverandmouseout
toggle
togglebetweentwofunctions,triggered
bymouseclick
The Event object
bla.event(function(evt) {
// evt is the event object
var xPos = evt.pageX; // dist from window left
var yPos = evt.pageY; // dist from window top
var xPosAbs = evt.screenX; // dist from screens left
var yPosAbs = evt.screenY; // dist from screens top
var shiftPressed = evt.shiftKey; // true if shift was
// pressed
var keycode = evt.which; // the keycode of the key pressed
var trgElement = event.target; // the element that was
// the target of the event,
// e.g. click()
});
Manipulating elements:
attribute values and CSS
Adding stuff to a page
var endString = "<p>Hello, I am some info, added at the
end of the element content.</p>";
var begString = "<p>Hello, I am some info, added to the
beginning of the element content</p>";
// Append something to the end of the infobox element
$("infobox").append(endString);
$("infobox").prepend(begString);
Removing and
replacing content
// remove an element from the DOM
$("#message1").remove();
// replace an element in the DOM with another element
$("#message2").replaceWith("<p>Added to cart</p>");
Reading, changing and
adding attributes
// read the value of an attribute
var imageSrc = $("#currentImage").attr("src");
// change the value of an attribute
var nextImage = "image2.jpg";
$("#currentImage").attr("src", nextImage);
// add an attribute to an element
$("#infobox").attr("style", "background-color: #888");
// remove an attribute + value from an element
$("#infobox").removeAttr("style");
Adding and removing a class
// add the class active to an element
$("li:first").addClass("active");
// remove the class active from an element
$("li:first").removeClass("active");
// add the class selected if it is not there
// remove the class selected if it is there
$("li:first").toggleClass("selected")
Reading and changing
CSS properties
// read a css property value
var fontSize = $("h1:first").css("font-size");
// set a css property
$("h1:first").css("font-size", "12px");
// set multiple css properties
$("h1:first").css({"padding" : "4px",
"margin" : "50px"
});
Naming variables that will
refer to jQuery objects
// If you use both regular JavaScript DOM object and
// jQuery objects in your code, it can be helpful to
// prefix you jQuery variable with a $ sign
$listObject = $("li");
// regular DOM element array
listItems = document.getElementsByTagName("li");
Implicit iteration over the
result set
$("li").css("font-size", "12px");
jQuery implementsimplicit iterationwhichmeansthatyoucane.g.change
editcss propertiesofalltheobjects intheresultsetwithoutusingaloop!
Explicit iteration
$("li").each(function(i, element) {
$(element).css("font-size", "12px");
console.log(i);
});
Wecanalsoiterateovertheresultsetusingexplicitlyusing the$().each
function.The$().each functioncanoptionally passanindexandan
elementtothespecified handler.
Explicit iteration
$("li").each(function() {
$(this).css("font-size", "12px");
});
Thehandler giventothe$().each functiondoes nothavetousetheindex
orelementthough.Wecaninsteadusethe$(this) reference.
$(this) is not this
// $(this) is the jQuery object
// this - without surrounding $() is the DOM element
// apply css to p element in the result set
$("p").each(function() {
$(this).css("color","#F00");
});
// using the DOM object
$("p").each(function() {
this.style.color="#F00";
});
Animation in jQuery
Animation
⁃ show, hide, toggle
⁃ fadeIn,fadeOut,fadeToggle, fadeTo
⁃ slideDown, slideUp, slideToggle
⁃ generalanimatefunction
show, hide, toggle
// hide contentboxes
$("#button1").click(function() {
$("div.contentbox").hide(1000);
});
// show contentboxes
$("#button2").click(function() {
$("div.contentbox").show(1000);
});
// toggle visible state of contentboxes
$("#button3").click(function() {
$("div.contentbox").toggle(1000);
});
fadeIn, fadeOut, fadeToggle,
fadeTo
// fade out contentboxes
$("#button1").click(function() {
$("div.contentbox").fadeOut(1000);
});
// fade in contentboxes
$("#button2").click(function() {
$("div.contentbox").fadeIn(1000);
});
// toggle fade state of contentboxes
$("#button3").click(function() {
$("div.contentbox").fadeToggle(1000);
});
// fade to a .50 opacity
$("#button3").click(function() {
$("div.contentbox").fadeTo(1000, .50);
});
slideUp, slideDown,
slideToggle
// slide up contentboxes
$("#button1").click(function() {
$("div.contentbox").slideUp(1000);
});
// slide down contentboxes
$("#button2").click(function() {
$("div.contentbox").slideDown(1000);
});
// toggle slide state of contentboxes
$("#button3").click(function() {
$("div.contentbox").slideToggle(1000);
});
Chaining jQuery and
animation
⁃ MostjQueryfunctions returntheresultset.
⁃ Thismeansthatisyou wanttodomorethanonething on
thesameresultset,youcanchainthesefunction calls
together.
Chaining jQuery and
animation
$("h1").css("font-size", "3em").css("font-size", "2em");
$("h1").animate({"font-size", "3em"}).css("font-size",
"2em");
General animation of CSS
changes using .animate()
// animate({css changes}, duration
$(".box").animate({
// css stuff
"width": '50px'
},
// duration of animation
1500
);
The animate() function relative change
//relative change of css using += and -=
$(".box").animate({
// css stuff
'left': '+=50px'
},
// duration of animation
1500
);
Fading elements using a delay –
setTimeout()
// setTimeout(function, delay)
function fadeAll(selector) {
$(selector).each(function(i, element) {
$(element).css({'opacity':1});
// delay the animation
setTimeout(function() {
// animate opacity change
$(element).animate( { "opacity": 0.0 }, 450);
},
// each element is delayed by 500ms + 500ms *
position in list
500 + ( i * 500 ));
});
}
Making it all stop
$(selector).stop();
Describing interaction
⁃ Wordsarenotenough. Weneedtousevisual
descriptions.
⁃ Wireframes
⁃ Statetransition diagrams
Wireframes
Paperprototyping
Planlayoutforcontent
State transition diagrams
For describing interaction,
we can combine these two
Showing a message box
Popping out a menu bar
Showing and hiding text
Adding things to a shopping list
Download