Date post: | 05-Apr-2017 |
Category: |
Design |
Upload: | booknet-canada |
View: | 169 times |
Download: | 4 times |
JAVASCRIPT AND EPUB:Making Interactive Ebooks
christinatruong.com @christinatruong
ebookcraft - March 22, 2017
Slides (PDF) bit.ly/ebookcraft-slidesOnline editor codepen.io
#EBOOKCRAFT JS WORKSHOP@christinatruong
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
HTML defines the content. CSS adds presentational styles. JavaScript adds interaction.
#EBOOKCRAFT JS WORKSHOP@christinatruong
What does this mean for ebooks?
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
JavaScript and EPUB3Adding interactivity can enhance the reading experience.
• Drag and move items on the page • Interactions can be based on specific user input • CSS animations, audio & video can be triggered
by specific actions instead of starting right away • and more!
Further Reading: EPUB3 Now! at IDPF DigitalBook World 2013
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
What is JavaScript?• Programming language
• Different programming languages have different syntaxes
• Programs, or scripts, are a set of instructions for the computer to execute
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
Writing a Program1. Define the goal
• Create a "choose your own adventure" story
2. Break it down into small steps or a series of tasks
• (1) Select an option, (2) update the sentence with the selected word, (3) trigger the corresponding animation
3. Code each step with HTML, CSS and JavaScript
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
JavaScript and ProgrammingProgramming languages tend to have more complexities than HTML or CSS.
The basic building blocks of programming includes many different concepts and has more syntax rules to follow.
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
Today you will learn about…• functions
• variables
• objects
• for loop
• conditionals
• concatenation
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
#EBOOKCRAFT JS WORKSHOP@christinatruong
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
Project Plan1. Select an option
(a) Listen for click / tap event
2. Update the sentence with the selected word (a) Store the selected option (b) Grab the blank text container (c) Update it with the selected word
3. Trigger the corresponding animation (a) Grab the animation wrapper (b) Add a class attribute and corresponding class name
Part 1: Create a set of instructions
#EBOOKCRAFT JS WORKSHOP@christinatruong
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
Functions• Used to execute a set of instructions
• Can also be reused throughout the program
• There are pre-defined functions in the language
prompt()//createsadialoguebox
Further reading: Mozilla Developer Network (MDN) - prompt()
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
Creating Your Own Functions• Defining it first with the keyword function • Give the function a name and parentheses • Add the instructions within the curly braces {} • Call the function to execute it
functionmyFunction(){//instructionshere}
myFunction();
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
Functions and ArgumentsArguments can be used to pass data into a function. Reuse the function with different arguments.
//createsanemptydialogueboxprompt()
//createsadialogueboxwithamessage.prompt("Whatisyourname?")prompt("Whatisthedate?")
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
StatementsStatements are instructions given to the computer.
Single line statements end with a semi-colon to indicate the end of the instruction.
prompt();prompt("Whatisyourname?");
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
Block statements group statements into code blocks and are enclosed by a pair of curly brackets {}.
myFunction(){prompt("Whatisyourname?");}
Block Statements
Single line statements must end in a semi-colon. Block statements do not need to end in a semi-colon.
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
Leave comments to organize your code or leave notes for yourself and others.
Comments
//DefiningthefunctionfunctionmyFunction(){console.log("hello");}
//CallingthefunctionmyFunction();
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
There are two styles of writing comments.
Comments
//Thisisasinglelinecomment.//Youcanusemanysinglelinecomments.//Justaddthedoubleforwardslashtoeveryline.
/*Thisisanotherwaytowritemulti-linecomments.Anycharacterscanbeaddedwithinthisblock.*/
Exercise time!
#EBOOKCRAFT JS WORKSHOP@christinatruong
1. Open a new pen in codepen.io: Create > New Pen1
2. Update the settings in codepen.io to disable auto-update. Settings > Behaviour > uncheck ENABLED > Save & Close
2
2
1
3
4
#EBOOKCRAFT JS WORKSHOP@christinatruong
3. (Optional) Change View to move the HTML, CSS and JS panels.1
2
#EBOOKCRAFT JS WORKSHOP@christinatruong
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
ExerciseIn your editor, add the prompt() function.
Try it with and without an argument to compare the difference.
prompt();prompt('Whatisyourname?');
Important! When passing an argument, use single or double quotes. (More on this later).
Where did it go?
#EBOOKCRAFT JS WORKSHOP@christinatruong
Part 2: Storing data
#EBOOKCRAFT JS WORKSHOP@christinatruong
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
Variables• Similar to a container or a box
• Used to store values/information
• Values can be used when you need them
ExampleUse a variable to store a customer's name. Then, use the stored data to output the customer's name into a confirmation email.
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
Declaring a Variable• To use a variable, declare it first • Use the keyword var and name the variable • Assign a value and end the command with a semi-colon
varfirstname;firstname="Christina";
• Variables can also be declared & assigned in one line. varfirstname="Christina";
Further reading: Understanding let and const
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
Naming Conventions• Variables cannot contain spaces, use camelCase
• JavaScript is case-sensitive
• Use descriptive names
• Cannot start with a number
varsubmitButton;//DescriptivevarsubmitBtn;//Commonabbreviationfor"button"varsb;//Notdescriptive
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
• Numbers — integers & decimals (e.g. 10, 10.001)
• Strings — characters including spaces, contained in quotes
• Booleans — true or false (keyword)
• Undefined — means “I don’t have a value”
• Null — means “I have a value of nothing”
• Objects
• Functions
Data / Value Types
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
The ConsoleA browser tool used to interact directly with the code in any web page. Check for errors, log diagnostic info, test code and more.
codepen.io console tool
#EBOOKCRAFT JS WORKSHOP@christinatruong
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
The console tool is included in all modern browsers and can be used to interact with any web page.
Chrome browser console tool
#EBOOKCRAFT JS WORKSHOP@christinatruong
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
Browser Console Tool Resources• Using the Browser Console:
wickedlysmart.com/hfjsconsole
• Chrome DevTools: developers.google.com/web/tools/chrome-devtools
• Firefox Developer Tools: developer.mozilla.org/en-US/docs/Tools/Browser_Console
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
Testing in the ConsoleUse the following method to log information and data to the console.
//syntaxconsole.log(argument);//examplevarfirstname="Christina";console.log(firstname);
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
ExerciseUse a variable to store the prompt() input data.Use console.log() to output the answer into the console.
//option1varname=prompt("Whatisyourname?");console.log(name);
//option2varquestion="Whatisyourname?";varanswer=prompt(question);console.log(answer);
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
WhitespaceRefers to blank or space characters, tabs & line breaks. JavaScript ignores whitespace in some instances.
varname="ChristinaTruong";//willbothdisplaythesamevarname="ChristinaTruong";
Whitespace matters when used in a string or using keyword.
varname="ChristinaTruong";//Willshowwithnospacevarname="ChristinaTruong";//notvalid
#EBOOKCRAFT JS WORKSHOP@christinatruong
Project Starter Files: bit.ly/ebookcraft-start
(codepen)
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
Project SetupStarter code: bit.ly/ebookcraft-start
Fork the pen to create your own copy.
• If you have an account, it will save to your profile
• If you do not have an account, it still generates a unique url that you can edit and save changes to
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
1a. Project Exercise1. Select an option
(a) Listen for click / tap event
Add an onclick attribute to the HTML button to initiate the interaction.
<button onclick="">starry</button> <button onclick="">snowy</button>
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
2a. Project Exercise2. Update the sentence with the selected word
(a) Store the selected option• Create a function to execute when the button is clicked
functionselect(){//instructionshere}
• Pass in the value of the selected option & output it to the console functionselect(word){console.log(word);}
• Call this function to execute these steps. select('starry');orselect('snowy');
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
2a. Project ExerciseAdd the function to your projects.
functionselect(word){console.log(word);}
Call the function in the button to trigger the function when clicked. Add an argument to pass the value into the function.
<button onclick="select('starry');">starry</button> <button onclick="select('snowy');">snowy</button>
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
2b & 2c. Project Exercise2. Update the sentence with the selected word
(b) Grab the blank text container (c) Update it with the selected word
We'll need to update the function with the following instructions:
functionselect(word){//GrabtheblanktextHTMLcontainer//Replacethecontainer'scontentwiththeselectedword}
Part 3: Manipulating HTML Objects
#EBOOKCRAFT JS WORKSHOP@christinatruong
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
The Document Object ModelWeb pages — the browser document, is made up of many blocks. Each HTML element is an object.
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
Variables vs ObjectsA variable holds one value. Access the value using the name.
varfood="pizza";console.log(food);//returnspizza
An object holds a collection of values. Assign and access the property values using dot notation.
varpizza={};pizza.crust="thin";pizza.meat="pepperoni";pizza.veg="mushrooms";console.log(pizza.crust);//returnsthin
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
Objects, Functions and MethodsMethods are just like functions, except they are applied to objects.
Functions run on their own.
//functionalert("Hello!");
//methodattachedtoanobjectdocument.write("Hello!");
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
querySelector()When applied to the document object, it returns the first matching element.
document.querySelector('.word');
<p>It was a <span class="word">______</span> night.</p>
Further reading: MDN: querySelector()
The selector can be any CSS selector, passed into the method as a string.
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
querySelector()Use a variable to hold the selected HTML element (the container for the word to be updated).
functionselect(word){//GrabtheblanktextHTMLcontainervarupdateWord=document.querySelector('.word');}
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
innerHTMLinnerHTML is a property, not a method. (Hint: there's no parentheses!)
Properties are used to get or set a value of an object. Remember the pizza object?
pizza.crust="thin";pizza.meat="pepperoni";
Use innerHTML to set & update the word in the sentence.varupdateWord=document.querySelector('.word');updateWord.innerHTML=word;
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
2b. & 2c. Project Exercise
functionselect(word){//GrabtheblanktextHTMLcontainer
varupdateWord=document.querySelector('.word');//Replacethecontainer'scontentwiththeselectedword
updateWord.innerHTML=word;}
Update the function.
Further reading: MDN innerHTML
Part 4: Add CSS Animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
3a. Project Exercise 3. Trigger the corresponding animation
(a) Grab the animation wrapper
<div id="wrapper"> <span class="animation"></span> </div>
varanimation=document.querySelector('#wrapper');
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
3b. Project Exercise3. Trigger the corresponding animation
(b) Add a class attribute and corresponding class name
Use the setAttribute() method to add and set the value of the attribute.
Syntax: setAttribute(attributeName,attributeValue);
Further reading: MDN - setAttribute()
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
setAttribute()If the attribute already exists in the selected element, the value is updated; otherwise a new attribute is added with the specified name and value.
varanimation=document.querySelector('#wrapper');animation.setAttribute('class',word);
<div id="wrapper" class="selected-option"></div>
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
3a. & 3b. Project Exercise
functionselect(word){//GrabtheblanktextHTMLcontainervarupdateWord=document.querySelector('.word');//Replacethecontainer'scontentwiththeselectedwordupdateWord.innerHTML=word;//Grabstheanimationwrapperdivvaranimation=document.querySelector('#wrapper');//Addsaclassattributewiththeselectedoptionvalueanimation.setAttribute('class',word);}
Update the function.
It works!Sorta…
#EBOOKCRAFT JS WORKSHOP@christinatruong
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
HTML & JavaScriptIt works! But there's only one star or snowflake.
What if you want more?
You can add it manually or use JavaScript to generate additional HTML elements.
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
HTMLThis is what the HTML needs to look like to have multiple snowflakes or stars.
<div id="wrapper"> <span class="animation"></span> <span class="animation"></span> <span class="animation"></span> . . . </div>
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
CSSThe top and bottom values should be different to position the elements in different parts of the page.
.snowflake1 { top: 0px; left: 400px; }
<span class="animation snowflake1"></span> <span class="animation snowflake2"></span>
.snowflake2 { top: -100px; left: 200px; }
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
JavaScript & innerHTML
varanimation=document.querySelector('#wrapper');animation.innerHTML='<spanclass="animation"style="top:0px;left:400px;"></span>'
Remove the <span> from the current HTML and use innerHTML to add the HTML and CSS into the wrapper.
The HTML and inline CSS will be added using innerHTML.
<div id="wrapper"></div>
We're not done yet!
#EBOOKCRAFT JS WORKSHOP@christinatruong
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
ConcatenationIf you use the + operator with numerical values, it will add the values.
varnumber=2+2;//result:4
varnumber=3;varaddIt=number+5;//result:8
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
ConcatenationIf you use the + operator with at least one string, it will combine the outputs.
varnumberAndString="3"+5;//result:35
varexample="Hello."+"MynameisChristina.";//Result:Hello.MynameisChristina;
varexample="Hello.";example+="MynameisChristina.";//Result:Hello.MynameisChristina;
Further reading: String Concatenation and String Operators
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
Add Multiple ElementsUse a for loop to generate multiple elements. for(vari=0;i<5;i++){animation.innerHTML+='<spanclass="animation"style="top:0px;left:400px;"></span>';}
i refers to the index and starts at 0
If i is less than five, add 1 to continue the loop
+= the HTML markup will be concatenated and appended to the end of the previous value every time it loops.
Further reading: MDN - Loops and Iteration
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
Add Multiple Elementsfor(vari=0;i<5;i++){animation.innerHTML+='<spanclass="animation"style="top:0px;left:400px;"></span>';}
This will result in 5 new elements added dynamically into the HTML. But they have the same position values.
<span class="animation" style="top:0px;left:400px;"></span> <span class="animation" style="top:0px;left:400px;"></span> <span class="animation" style="top:0px;left:400px;"></span> <span class="animation" style="top:0px;left:400px;"></span> <span class="animation" style="top:0px;left:400px;"></span>
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
Add Multiple ElementsEvery time you press a button option, the loop will continue to append the <span> elements.
Set the innerHTML to blank first, to clear any elements and re-start with an empty animation wrapper.
animation.innerHTML="";for(vari=0;i<5;i++){animation.innerHTML+='<spanclass="animation"style="top:0px;left:400px;"></span>';}
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
Randomize the CSS PositionGenerate random values for the top and left CSS properties using the function below. //GeneratearandomintegerbetweentwovaluesfunctiongetRandomInt(min,max){min=Math.ceil(min);max=Math.floor(max);returnMath.floor(Math.random()*(max-min))+min;}
Further Reading: MDN - Math.random()
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
Randomize the CSS PositionUse variables as a placeholder to generate random top and bottom values for each <span> element. //GeneraterandomvaluesbetweentwovaluesvartopValue=getRandomInt(0,600);varleftValue=getRandomInt(0,1200);
The variables and HTML must be concatenated because we are mixing strings and variables.
animation.innerHTML+='<spanclass="animation"style="top:'+topValue+'px;left:'+leftValue+'px;"></span>'
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
Final Updatefunctionselect(word){//GrabtheblanktextHTMLcontainervarupdateWord=document.querySelector('.word');//Replacethecontainer'scontentwiththeselectedwordupdateWord.innerHTML=word;//Grabstheanimationwrapperdivvaranimation=document.querySelector('#wrapper');//Addsaclassattributewiththeselectedoptionvalueanimation.setAttribute('class',word);//Resetsandremovesanypreviouslyaddedspanelement.animation.innerHTML="";//Addsmultipleanimationelementsfor(vari=0;i<5;i++){vartopValue=getRandomInt(0,600);varleftValue=getRandomInt(0,1200);animation.innerHTML+='<spanclass="animation"style="top:'+topValue+'px;left:'+leftValue+'px;"></span>'
}}
Bonus!
#EBOOKCRAFT JS WORKSHOP@christinatruong
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
if / else ConditionalsTo make the snow appear to "fall" at different starting points, use a negative margin value.
Use if/elseto determine which option has been selected.
if(word==="snowy"){topValue=getRandomInt(-1000,0);leftValue=getRandomInt(0,1200);}else{topValue=getRandomInt(1,600);leftValue=getRandomInt(1,1200);}
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
Update the Loopfor(vari=0;i<5;i++){
vartopValue;varleftValue;
if(word==="snowy"){topValue=getRandomInt(-1000,0);leftValue=getRandomInt(0,1200);
}else{topValue=getRandomInt(1,600);leftValue=getRandomInt(1,1200);}animation.innerHTML+='<spanclass="animation"style="top:'
+topValue+'px;left:'+leftValue+'px;"></span>'}
You did it!
#EBOOKCRAFT JS WORKSHOP@christinatruong
This slide is preset with animations
#EBOOKCRAFT JS WORKSHOP@christinatruong
Extra Resources• idpf: EPUB Content Documents - Scripting
• idpf: JavaScript epubReadingSystem Object
• javascript.com - Tutorials
• eloquentjavascript.net - online book including interactive demos
Thank you!
#EBOOKCRAFT JS WORKSHOP@christinatruong