Você está na página 1de 10

1/31/2014

1
'O O '!
( '' , '/^O)
CS171 Lab1
1/31/14
'OOUO O OO,
HTML&CSS
Buildandstyleabasicwebpage
Javascript
Introduce&reviewJavascript syntaxandstyle.
Linktolibraries&startwritingJavascript.
LearnabouttheconsoleandhowtouseChromesinspectortool.
LearnbasictechniquestodebuggingJavascript
Homework1
Getstartedwithrunningabasicwebserver&understandingthecode
O
Usefuldevelopmenttools.
Targetplatformforallproblemsets.
Yourwork(assignments,etc)mustbefunctionalinChrome.
\ '!
\ '!
HypertextMarkupLanguage(HTML)
Markuplanguage,notaprogramminglanguage.
Providesinstructiononhowtorenderapage.
HTMLisconsistsofelements builtwithstarttagsandendtags.
Starttagexample:<head>
Endtagexample:</head>
Elementexample:<head>.(stuffgoeshere).</head>
' '!, '' '^ O^O
1/31/2014
2
' '!, '' '^ O^O
HTMLincludeselementswhichincludeimages,objects,videos,lists,links,quotes,and
otheritems..therearemanytypesoftags!
(usegoogle!)
Tagsalsoincludeattributes.
Example:anchortag.
<a></a>
Addingthehref attributeallowsforthecreationofalink
<ahref="https://www.cs50.net/">CS50</a>.
'! ,OU ^ O O O
<title>My webpage</title>
Put s t he t i t l e of t he web page i n t he t i t l e bar of your br owser .
<a href=www.example.com>My link</a>
Cr eat es l i nks! Use t he hr ef at t r i but e t o r epr esent t he ur l .
<img> or <img />
I ndi cat es t hat an i mage wi l l be shown on t he page. Use t he sr c at t r i but e
t o l i nk t o t he i mage, use t he al t at t r i but e i s used t o pr ovi de a shor t
descr i pt i on t o t he i mage.
<p>This is a paragraph!</p>
Cr eat es par agr aph t ext i n t he document .
<h1> to <h6>
<h1>Some header</h1>
Pr ovi des header st r uct ur e t o your t ext . <h1> i s t he most i mpor t ant
headi ng, <h2> i s l ess i mpor t ant , et c
<ol>...</ol>
Cr eat es an or der ed l i st ( l i ke a number ed l i st )
<ul>...</ul>
Cr eat es an unor der ed l i st ( l i ke bul l et poi nt s)
<li>List item </li>
Cr eat es an i t emt hat bel ongs t o a l i st
<html>...</html>
Cr eat es t he ent i r e HTML cont ai ner .
<head>...</head>
Cr eat es t he header ( gener al l y wher e t he t i t l e and l i nks t o st yl e
sheet s/ scr i pt s ar e f ound)
<body>...</body>
Cr eat es t he sect i on of ht ml t hat cont ai ns cont ent
<table>...</table>
Cr eat es a t abl e i n t he document .
<tr>...</tr>
Speci f i es a t abl e r ow i n a t abl e.
<td>..</tr>
Speci f i ces a t abl e cel l i n a t abl e r ow
<link rel="stylesheet" type="text/css" href="theme.css">
Poi nt s t o an ext er nal f i l e i s l i nked t o t he cur r ent ht ml document ( of t en
used f or CSS ext er nal st yl esheet s)
<div>...</div>
A di vi si on of a page. Used as an addi t i onal means t o pr ovi de st r uct ur e t o
HTML.
<script>...</script>
I ncl udes t ext i nsi de t hi s t ag as scr i pt , most commonl y t ext / j avascr i pt .
<form>..</form>
Ar ea encl osed by t hi s t ag i s an HTML f or mt hat can accept user i nput .
<input></input> or <input />
Used i nsi de an HTML f or mand i s used t o accept user i nput or submi t t he
i nput , has at t r i but es t ype and l abel whi ch speci f y t ype of f or mi nput
el ement .
<!-- ... >
HTML comment t ag. Used t o add t ext t o your document t hat wi l l not be
di spl ayed i n t he br owser and i s usef ul t o document t he page.
' '!, '' '^ U
HTMLelementscommonlyhaveclass
andidattributes.
Theseattributesareincludedinsidethe
openingtag.
<h1 id=main_header>Visualization of
Taxes</h1>
<a class=navigation_link
header_link>Menu</a>
<a hr ef ="ht t ps: / / www. cs50. net / "
i d=cs50_l i nk cl ass=menu_l i nk>CS50</ a>
Theseattributesareusedtoselect
HTMLelementslaterthroughCSS/
Javascript
' U
class=example_class1
example_class2
Eachelement canhave
multipleclasses,
separatedbyspaces.
The class attribute can
be appliedformultiple
elmenets
' U
id=example_id
Eachelement canonly
have one class.
The idattribute should
be unique forone
element.
'! O''O UU
YourwebbrowserrendersHTMLwithaDocumentObjectModel(DOM):
Note:objectsintheDOMtreecanbeadded/removed/manipulatedbyJavascript
WellcheckthisoutlaterinChromeselementinspector
<ht ml >
<head>
<t i t l e>My t i t l e</ t i t l e>
</ head>
<body>
<a hr ef =>My l i nk</ a>
<h1>My header </ h1>
</ body>
</ ht ml >
O '!
Youdontneedtomemorizeallyourtags!
Butyoushouldknowhowtouseclass andidattributesforHTMLelements.
TheseattributeswillhelplabelHTMLelementssoyoucandothingswiththem.
Openupyourfavoritetexteditorandcreateanewfilecalledindex.html.
OO 'OO OOO
<ht ml >
<head>
<t i t l e>My Fi r st Vi sual i zat i on! </ t i t l e>
<! - - My f i r st vi sual i zat i on, cr eat ed by __; 1/ 28/ 14 - - >
</ head>
<body>
<h1>My Fi r st Vi sual i zat i on</ h1>
<p>Thi s i s par agr aph t ext descr i bi ng my f i r st vi sual i zat i on. </ p>
<but t on>Thi s i s a but t on f or my vi sual i zat i on</ but t on>
<t abl e>
<t head>
<t r >
<t h>Header 1</ t h>
<t h>Header 2</ t h>
</ t r >
</ t head>
<t body>
<t r >
<t d>Cel l 1</ t d>
<t d>Cel l 2</ t d>
</ t r >
<t r >
<t d>Cel l 3</ t d>
<t d>Cel l 4</ t d>
</ t r >
</ t body>
</ t abl e>
</ body>
</ ht ml >
1/31/2014
3
\
\
CascadingStyleSheets
Stylesheet languagefortheweb,makeswebpageslookgood.
Includesthefonts,colors,andmanyotherpropertiesforwebpages.
CSSisappliedtoHTMLelements,withCSSproperties
ExamplesofCSSproperties:
col or : r ed
backgr ound- col or : #f f f ;
paddi ng: 20px;
f ont - si ze: 18px;
di spl ay: none;
'O OO ,OU U
<t abl e st yl e=mar gi n- t op: 20px; ></ t abl e> Inline(insidetheHTML):
<st yl e t ype=" t ext / css">
#dat at abl e {
mar gi n- t op: 20px;
}
</ st yl e>
Inthedocument:
<l i nk hr ef =" pat h/ t o/ f i l e. css" r el ="st yl esheet "> Inaseparatefile:
'O OO ' O
InaCascadingStyleSheetfileyouselectelementsbasedonclassandidattributesin
theHTML,thenapplyproperties.
1. AddclassandidattributestoHTMLelements:
Ex: <t abl e> to<t abl e i d=dat at abl e1 cl ass=dat ael ement >
2. AddCSSselectors totheseclasses/idsintheCSSdocument:
Usingaclass
Adda period(.)
beforetheclass,
usebrackets
. dat ael ement {
col or : r ed;
}
Usinganid
Adda hash(#)
beforetheid,
usebrackets
#dat at abl e{
col or : r ed;
}

TherearealotofdifferenttypesofselectorsandCSSproperties,wewonthavetimeto
coveritall.(googleisyourfriend)
CSSDemo
1. Createanewfilecalledstyles.cssinthesamedirectoryasthepreviousHTMLfileyou
workedon
2. Addthistoyourheader:
<l i nk hr ef =st yl es. css" r el =" st yl esheet ">
O^ 'O OO'
GoogleChromehasasetoftoolsthatmakesstylingandvisualizingtheHTMLdocument
easier:
Menu>Tools>DeveloperTools
or
Ctrl+Shift+I
or
Rightclickonwebpage>Inspectelement
1/31/2014
4
\
\
Aprogramminglanguageforwebbrowsersgenerallyexecutedclientside(in yourweb
browser)
Javascript codeiswritteninscriptswhicharerunwhenthepagerenders.
TherearetwowaystoincludeJavascript
Inthedocument:
<scr i pt t ype="t ext / j avascr i pt " >
al er t ( Thi s i s your f i r st l i ne of J avascr i pt ! ! ) ;
</ scr i pt >
Inaseparatefile:
<scr i pt sr c=vi z. j s" ></ scr i pt >
(thissimplyloadsthe content of the file asif it were Javascript)
AJavascript fileissimplyatextfilewitha.js extensionwhichcontainsJavascript.
\,
Javascript candoalot!
Example:respondingtoclicks,addingsvg (graphics)elements,creating
elementsfromdata,etc.
W3schools.com
1J1
Checkoutthebrowsermethodsat:http://overapi.com/javascript/
Ifyouarecompletelynew,alsorefertothetutorialat:
https://developer.mozilla.org/enUS/docs/Web/JavaScript/Guide
Forthoseexperiencedwithprogramming,thesyntaxissimilartoCandPHP.
Programming(withJavascript)canbefrustrating!
1J1 '
<scr i pt >
al er t ( hel l o wor l d! ) ;
/ / Thi s i s your f i r st comment !
</ scr i pt >
This is actuallyjust HTML tellingthebrowser that
Javascript is coming.
This is alineofJavascript. Herewecall thealert()
function with thestringhelloworld!Thealert()
function displays amessagebox in your browser.
Youcanincludescripttagsanywhereinyourdocument.Thepagewillexecute
theJavascript intheorderthatisincludedinthepage.
You can createcomments in Javscript by
adding// tothebeginning oftheline.
Thebrowser will ignoretheselines.
1J1 'UO
Functionsaresetsofcodethatareexecuted.Toexecuteapieceofcode,youcalla
function.Youcanalsocallafunctionwitharguments.
Somefunctionsarealreadydefinedbythebrowser(thisiswhatgivesusinteractivitywith
thewebbrowser)!
Intheearlierexample,wecalledthefunctionalert withtheargumenthelloworld.
<scr i pt >
al er t ( hel l o wor l d! ) ;
</ scr i pt >
//(thefunction alert is alreadydefined in thebrowser)
1/31/2014
5
1J1 'UO (O)
TwowaystodefinefunctionsinJavascript:
Torunthecodeinthefunction,simplycall
<scr i pt >
myf i r st f unct i on( ) ;
</ scr i pt >
f unct i on myfirstfunction( ) {
/ / some code to be executed
}
var myfirstfunction = function( ) {
/ / some code to be executed
}
1J1 'UO (O, .)
Youdontalwaysneedfunctions!
Anycodeinthescripttagisautomaticallyrunasthepagereachesthescripttag.
<scr i pt >
al er t ( Hel l o wor l d) ;
/ / Thi s code i s r un as t he page r edner s
</ scr i pt >
Whyusefunctions?
Topassinargumentsandpreventcoderedundancy/repetition.
Tousefunctionsthathavealreadybeenwrittenforyou.
Tomakeyourcodebetter!(andotherreasons)
1J1 \'
Javascript allowsyoutostorevariables (values)tobeusedandmanipulatedlater.Creatinga
variableinvolvesdeclaringavariableandnaming thevariable.Javascript isdynamically
typed(soyoudontneedtodeclarewhattype ofvalueitis):
<scr i pt >
var num1 = 1;
var num2 = 2;
var st r i ng = t wo;
var bool = f al se;
</ scr i pt >
Doyouneedtousevar whendeclaringthevariableforthefirsttime?
Generally,yes.Whileyourcodemayworkwithoutthevardeclaration,thescopeof
yourvariableisglobal.Unlessyouknowwhatyouredoing,alwaysusevar.
1J1 \' O
Javascript variableshavethescopeinwhichtheyaredeclared:
<scr i pt >
var g = " gl obal " ;
f unct i on go( ) {
var l = " l ocal " ;
}
go( ) ;
al er t ( g) ; / / al er t s wi t h gl obal
al er t ( l ) ; / / t hr ows a r ef er ence er r or
</ scr i pt >
1J1 O
<scr i pt >
var num1 = 1;
var num2 = 2;
var st r 2 = t wo;
var st r 3 = t hr ee;
var bool = f al se;
var num3 = num1 * num2; / / 2
var f oo = st r 2 + st r 3; / / t wot hr ee
var bar = ! bool ; / / t r ue
var baz = num1 + st r 3; / / 1t hr ee
</ scr i pt >
1J1 ,
Javascript allowsyoutocreatearrays whichcanstorerelatedvalues.Creatinganarrayis
similartocreatingavariable:
<scr i pt >
var days = [ Mon , Tue , Wed ]
al er t ( days[ 0] ) ; / / al er t s user wi t h Mon
var f oo = days[ 1] +days[ 2] ; / / TueWed
al er t ( days. l engt h) ; / / al er t s user wi t h 3
</ scr i pt >
Arraysarezeroindexed.
Whichmeansthatthefirstiteminthearrayhasanindexvalueofzero.
Arrayshavealengthproperty.
Toaccessthelengthofalist,use(arrayname).length
1/31/2014
6
1J1 , (.)
JavaScriptincludesanumberofmethodsforarraymanipulation:
Array.shift()
Removesthefirstitemfromanarray,returnstheremovedelement
Array.pop()
Removesandreturnsthelastitem
Array.push()
Addsone(ormore)itemstotheendofanarray
seedocumentationformore.
i f ( condi t i on)
{
/ / do t hi s
}
el se i f ( condi t i on)
{
/ / do somet hi ng el se
}
el se
{
/ / do somet hi ng di f f er ent
}
1J1 O O OO' (1)
<scr i pt >
var days = [ Mon , Tue , Wed ] ;
i f ( days[ 0] == Mon )
{
al er t ( Monday) ;
}
el se i f ( days[ 0] == Tue )
{
al er t ( Tuesday)
}
el se
{
al er t ( Wednesday) ;
}
</ scr i pt >
Ifstatements
Howitworks Example
/ / For l oops
f or ( i ni t i al i zat i ons; condi t i on; updat es)
{
/ / do somet hi ng r epeat edl y
}
/ / Whi l e l oops
whi l e ( condi t i on)
{
/ / do somet hi ng r epeat edl y
}
1J1 O O OO' ()
<scr i pt >
var days = [ Mon , Tue , Wed ] ;
/ / For l oop 1
f or ( var i i n ar r ay) {al er t ( days[ i ] ) ; }
/ / For l oop 2
f or ( var i =0; i <days. l engt h; i ++) {
al er t ( days[ i ] ) ;
}
/ / Whi l e l oop var i =0;
whi l e( i <days. l engt h) {
al er t ( days[ i ] ) ;
i ++; / / Pr event i nf i ni t e l oops
}
</ scr i pt >
Differenttypesofloops
Howitworks Example
1J1 OO'
GoogleChromehasaJavascript consolethatmakesdebugging(finderrorsinyourcode)
andinteractingwithyourJavascript easier:
Menu>Tools>JavaScriptConsole
or
Ctrl+Shift+J
or
Rightclickonwebpage>Inspectelement>Console
1J1' OO'
Intheconsole:
YouwillseeerrorsthatoccurredwhilerunningyourJavascript
Messagesthatyousentyourselfviatheconsole.log()function
TheoutputfromJavascript thatyourunintheconsole.
1J1' OO'
Theconsole.logfunctionisincrediblyuseful.
Tryit!(intheconsole,youdontneedtowritescripttags,justtypeeachstatementin)
Theconsoleisagreatplacetoexaminethestructureandvalueofyourvariables.To
examinedata,useconsole.log(variable).
<scr i pt >
var days = [ Mon , Tue , Wed ] ;
f or ( var i i n days) {
consol e. l og( days[ i ] ) ;
}
</ scr i pt >
1/31/2014
7

OU '! '
\ OO
<> </> O
UO ''O cl i ckFunct i on
cl i ckFunct i on '' U
'
OO'
OO oncl i ck=" cl i ckFunct i on( ) O UO '^
' ,OU ', 'O UO OO'
'
HTML
A browser displays HTML,which
is rendered bythebrowser.
Provides structure
Follows thespecification of the
DocumentobjectModel (DOM)
CSS
Provides presentation(style,
layout,colors,etc)
Operates via selectors
CSS3
Javascript
Provides interaction
Programminglanguageused in
web browsers
\ \
WhatisSVG?
StandsforScalableVectorGraphics, astandardforgraphicsinwebpages.
SVGallowsustocreategraphicobjectsinmarkup,andalsomanipulatethem
withJavascript!
Example:
<svg xml ns=" ht t p: / / www. w3. or g/ 2000/ svg" ver si on="1. 1" >
<r ect wi dt h=" 300" hei ght =" 100" st yl e="f i l l : r gb( 0, 0, 255) ; st r oke- wi dt h: 1; st r oke: r gb( 0, 0, 0) " / >
</ svg>
SVGElementscanalsobestyledwithCSS
\, \
SVGallowsustobuildvisualizations!
O \
Browsethespecificationat:
http://www.w3.org/Graphics/SVG/IG/resources/svgprimer.html
Tagsyoumightwanttotry:
<rect></rect>
<circle></circle>
Togetstarted,addthistoyourindex.htmlfile:
<svg xml ns="ht t p: / / www. w3. or g/ 2000/ svg" ver si on="1. 1">
<r ect wi dt h="300" hei ght ="100" st yl e="f i l l : r gb( 0, 0, 255) ; st r oke- wi dt h: 1; st r oke: r gb( 0, 0, 0) " / >
<ci r cl e cx="80" cy="170" r ="40 f i l l ="yel l ow" st r oke="bl ue" / >
</ svg>
Again,SVGElementscanalsobestyledwithCSS
O '^O
Dontwastetimereinventingthewheel!
1/31/2014
8
O '^O
WhatifsomeonealreadymadelibrariestomakeprogramminginJavascript easier andfaster?
WhatifsomeonealreadycreatedCSSstylesheets thatincludestandardsincurrentUIdesign?
jQuery
MakesDOMmanipulation,
animation,eventhandling,
andAJAXeasierandsimple.
MostwidelyusedJavascript
library,manypluginsare
builtwithjQuery
Extremelypowerful.
D3.js
datadrivendocuments
SomeoverlapwithjQueryin
termsofeventhandling,
selection,etc.
Allowsforbindingofdata
toelements!
Bootstrap
Frontendframework
dependentonjQuery
Focusedonpresentation,
makeselementsacrossthe
webconsistent
Extremelypopular. Youll
probablyrecognizesome
(modified)bootstrapwhen
youseeit.
O '^O
HowdoyouincludejQuery,d3.js,andBoostrap?
http://d3js.org/
http://getbootstrap.com/
http://jquery.com/
IncludetheseelementsinyourHTMLheader:
<scr i pt sr c="ht t p: / / d3j s. or g/ d3. v3. mi n. j s" char set ="ut f - 8"></ scr i pt >
<scr i pt sr c="ht t p: / / code. j quer y. com/ j quer y- 1. 10. 1. mi n. j s"></ scr i pt >
<l i nk r el ="st yl esheet " hr ef =ht t p: / / net dna. boot st r apcdn. com/ boot st r ap/ 3. 0. 3/ css/ boot st r ap. mi n. css">
<scr i pt sr c=ht t p: / / net dna. boot st r apcdn. com/ boot st r ap/ 3. 0. 3/ j s/ boot st r ap. mi n. j s"></ scr i pt >
ThesetagsallowyoutoincludetheJavaScriptandCSSfileswrittenbyotherpeopleinto
yourHTMLdocument.(youcanalsodownloadthemlocallyandincludethemthatwayif
youdontalwayshaveinternetconnection).
,U, O, ' ^O
IfyouhavealreadyusedjQuery:
Thereissignificantoverlap:
jQueryisgenerallyusedtomanipulatetheDOM,d3.jsallowsfordatabinding
Youcouldwritewholebooksonhowtousetheselibraries.
Searchthedocumentation/Googleonwhatyourelookingfor.Thisisanimportantskill!
d3. sel ect ( ' #f oo' )
. st yl e( ' backgr ound' , ' #000' )
. on( ' cl i ck' , f unct i on( ) {})
. append( ' di v' ) ;
$( ' #f oo' )
. css( ' backgr ound' , ' #000' )
. cl i ck( f unct i on( ) {})
. append( $( ' <di v></ di v>' ) ) ;
O 'O^O 1
O'OO '
1. Gotohttps://github.com/CS171/HW1
2. Inalocationofyourchoice:
git clone https://github.com/CS171/HW1.git
Note:pleasecreaterepositorynamedcs171hw1lastnamefirstname
andcopythefilesoverwhenyousubmit.
O'OO '
1. Gotohttps://github.com/CS171/HW1
2. Inalocationofyourchoice:
git clone https://github.com/CS171/HW1.git
Note:pleasecreaterepositorynamedcs171hw1lastnamefirstname
andcopythefilesoverwhenyousubmit.
1/31/2014
9
'U
1. NavigatetotheHW1directorywhichyoujustcreated
2. Startalocalwebserverwiththefollowingcommand:
python -m SimpleHTTPServer
Note:youneedPythoninstalledforthis.(Youprobablyalreadyhavethis
installed;ifnot,askoneofusforhelp)
'U
1. NavigatetotheHW1directorywhichyoujustcreated
2. Startalocalwebserverwiththefollowingcommand:
python -m SimpleHTTPServer
Note:youneedPythoninstalledforthis.(Youprobablyalreadyhavethis
installed;ifnot,askoneofusforhelp)
'OO '^'
1. NavigatetotheHW1directorywhichyoujustcreated
2. Visitingthefollowingaddressinyourbrowser:
http://localhost:8000/table.html
'OO '^'
d3.tsv(url[, accessor][, callback])
IssuesanHTTPGETrequestforthetabseparatedvalues(CSV)fileatthe
specified url.
var t abl e = d3. sel ect ( " body" ) . append( " t abl e") ,
t body = t abl e. append( "t body") ;
var r ows = t body. sel ect Al l ( "t r " )
. dat a( dat a)
. ent er ( )
. append( " t r " ) ;
'OO '^' (.)
var t abl e = d3. sel ect ( "body" ) . append( " t abl e" ) ,
t body = t abl e. append( " t body" ) ;
var r ows = t body. sel ect Al l ( " t r " )
. dat a( dat a)
. ent er ( )
. append( " t r " ) ;
var cel l s = r ows. sel ect Al l ( " t d" )
. dat a( f unct i on( r ow) {
r et ur n d3. r ange( Obj ect . keys( r ow) . l engt h) . map( f unct i on( col umn, i ) {
r et ur n r ow[ Obj ect . keys( r ow) [ i ] ] ;
}) ;
})
. ent er ( )
. append( " t d" )
. t ext ( f unct i on( d) { r et ur n d; }) ;
}) ;
'OO '^' ()
var t abl e = d3. sel ect ( "body" ) . append( " t abl e" ) ,
t body = t abl e. append( " t body" ) ;
var r ows = t body. sel ect Al l ( " t r " )
. dat a( dat a)
. ent er ( )
. append( " t r " ) ;
var cel l s = r ows. sel ect Al l ( " t d" )
. dat a( f unct i on( r ow) {
r et ur n d3. r ange( Obj ect . keys( r ow) . l engt h) . map( f unct i on( col umn, i ) {
r et ur n r ow[ Obj ect . keys( r ow) [ i ] ] ;
}) ;
})
. ent er ( )
. append( " t d" )
. t ext ( f unct i on( d) { r et ur n d; }) ;
}) ;
1/31/2014
10
U^^,
HTML,CSS,andJavascript arethebuildingblocksoftheweb
experience.
SVGandd3.jsmakebeautifuldatavisualizationpossible.
UO
Addendum1:d3vsjQuery
http://www.macwright.org/presentations/dcjq/

Você também pode gostar