JAVASCRIPT AND EPUB:
Making Interactive Ebooks
christinatruong.com

@christinatruong
ebookcraft - March 22, 2017
Slides (PDF) bit.ly/ebookcraft-slides
Online editor codepen.io
#EBOOKCRAFT JS WORKSHOP

@christinatruong
#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?
#EBOOKCRAFT JS WORKSHOP

@christinatruong
JavaScript and EPUB3
Adding 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
bit.ly/ebookcraft-final
#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
#EBOOKCRAFT JS WORKSHOP

@christinatruong
Writing a Program
1. 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
#EBOOKCRAFT JS WORKSHOP

@christinatruong
JavaScript and Programming
Programming 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.
#EBOOKCRAFT JS WORKSHOP

@christinatruong
Today you will learn about…
• functions
• variables
• objects
• for loop
• conditionals
• concatenation
#EBOOKCRAFT JS WORKSHOP

@christinatruong
#EBOOKCRAFT JS WORKSHOP

@christinatruong
#EBOOKCRAFT JS WORKSHOP

@christinatruong
Project Plan
1. 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
#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()	//creates	a	dialogue	box
Further reading: Mozilla Developer Network (MDN) - prompt()
#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
function	myFunction(){	
		//	instructions	here	
}
myFunction();
#EBOOKCRAFT JS WORKSHOP

@christinatruong
Functions and Arguments
Arguments can be used to pass data into a function.
Reuse the function with different arguments.
//creates	an	empty	dialogue	box

prompt()	
//creates	a	dialogue	box	with	a	message.

prompt("What	is	your	name?")

prompt("What	is	the	date?")
#EBOOKCRAFT JS WORKSHOP

@christinatruong
Statements
Statements are instructions given to the computer.
Single line statements end with a semi-colon to
indicate the end of the instruction.
prompt();	

prompt("What	is	your	name?");
#EBOOKCRAFT JS WORKSHOP

@christinatruong
Block statements group statements into code blocks
and are enclosed by a pair of curly brackets {	}.
myFunction(){	
		prompt("What	is	your	name?");	
}
Block Statements
Single line statements must end in a semi-colon.
Block statements do not need to end in a semi-colon.
#EBOOKCRAFT JS WORKSHOP

@christinatruong
Leave comments to organize your code or leave notes
for yourself and others.
Comments
//	Defining	the	function		
function	myFunction(){	
		console.log("hello");	
}
//	Calling	the	function	
myFunction();
#EBOOKCRAFT JS WORKSHOP

@christinatruong
There are two styles of writing comments.
Comments
//	This	is	a	single	line	comment.	
//	You	can	use	many	single	line	comments.	
//	Just	add	the	double	forward	slash	to	every	line.	
/*		
			This	is	another	way	to	write	multi-line	comments.						
			Any	characters	can	be	added	within	this	block.	
*/
Exercise time!
#EBOOKCRAFT JS WORKSHOP

@christinatruong
1. Open a new pen in codepen.io: Create > New Pen
1
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
#EBOOKCRAFT JS WORKSHOP

@christinatruong
Exercise
In your editor, add the prompt() function.
Try it with and without an argument to compare the
difference.
prompt();

prompt('What	is	your	name?');	
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
#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
Example

Use a variable to store a customer's name. 

Then, use the stored data to output the customer's name into a
confirmation email.
#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
var	firstname;

firstname	=	"Christina";	
• Variables can also be declared & assigned in one line.
var	firstname	=	"Christina";
Further reading: Understanding let and const
#EBOOKCRAFT JS WORKSHOP

@christinatruong
Naming Conventions
• Variables cannot contain spaces, use camelCase
• JavaScript is case-sensitive
• Use descriptive names
• Cannot start with a number
var	submitButton;	//	Descriptive	
var	submitBtn;				//	Common	abbreviation	for	"button"	
var	sb;											//	Not	descriptive
#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
#EBOOKCRAFT JS WORKSHOP

@christinatruong
The Console
A 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
#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
#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
#EBOOKCRAFT JS WORKSHOP

@christinatruong
Testing in the Console
Use the following method to log information and data
to the console.
//syntax	
console.log(argument);	


//example	
var	firstname	=	"Christina";	
console.log(firstname);
#EBOOKCRAFT JS WORKSHOP

@christinatruong
Exercise
Use a variable to store the prompt() input data.

Use console.log() to output the answer into the console.
//	option	1	
var	name	=	prompt("What	is	your	name?");	
console.log(name);	
//	option	2	
var	question	=	"What	is	your	name?";	
var	answer	=	prompt(question);	
console.log(answer);
#EBOOKCRAFT JS WORKSHOP

@christinatruong
Whitespace
Refers to blank or space characters, tabs & line breaks.
JavaScript ignores whitespace in some instances.
var	name="Christina	Truong";	//	will	both	display	the	same

var	name	=	"Christina				Truong";	
Whitespace matters when used in a string or using
keyword.
var	name	=	"ChristinaTruong";	//	Will	show	with	no	space

varname	=	"Christina	Truong";	//	not	valid
#EBOOKCRAFT JS WORKSHOP

@christinatruong
Project Starter Files:
bit.ly/ebookcraft-start
(codepen)
#EBOOKCRAFT JS WORKSHOP

@christinatruong
Project Setup
Starter 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
#EBOOKCRAFT JS WORKSHOP

@christinatruong
1a. Project Exercise
1. 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>
#EBOOKCRAFT JS WORKSHOP

@christinatruong
2a. Project Exercise
2. Update the sentence with the selected word
(a) Store the selected option
• Create a function to execute when the button is clicked
function	select(){	
		//instructions	here	
}
• Pass in the value of the selected option & output it to the console
function	select(word)	{	
		console.log(word);	
}
• Call this function to execute these steps.
select('starry');	or	select('snowy');
#EBOOKCRAFT JS WORKSHOP

@christinatruong
2a. Project Exercise
Add the function to your projects.
function	select(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>
#EBOOKCRAFT JS WORKSHOP

@christinatruong
2b & 2c. Project Exercise
2. 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:
function	select(word)	{	
		//	Grab	the	blank	text	HTML	container	
		//	Replace	the	container's	content	with	the	selected	word	
}
Part 3: Manipulating
HTML Objects
#EBOOKCRAFT JS WORKSHOP

@christinatruong
#EBOOKCRAFT JS WORKSHOP

@christinatruong
The Document Object Model
Web pages — the browser document, is made up of
many blocks. Each HTML element is an object.
#EBOOKCRAFT JS WORKSHOP

@christinatruong
Variables vs Objects
A variable holds one value. Access the value using the name.
var	food	=	"pizza";	
console.log(food);//	returns	pizza	
An object holds a collection of values. Assign and access the
property values using dot notation.
var	pizza	=	{};	
pizza.crust	=	"thin";	
pizza.meat	=	"pepperoni";	
pizza.veg	=	"mushrooms";	
console.log(pizza.crust);//	returns	thin
#EBOOKCRAFT JS WORKSHOP

@christinatruong
Objects, Functions and Methods
Methods are just like functions, except they are
applied to objects.
Functions run on their own.
//	function	
alert("Hello!");		
//	method	attached	to	an	object	
document.write("Hello!");
#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.
#EBOOKCRAFT JS WORKSHOP

@christinatruong
querySelector()
Use a variable to hold the selected HTML element
(the container for the word to be updated).
function	select(word)	{	
		//	Grab	the	blank	text	HTML	container	
		var	updateWord	=	document.querySelector('.word');	
}
#EBOOKCRAFT JS WORKSHOP

@christinatruong
innerHTML
innerHTML 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.
var	updateWord	=	document.querySelector('.word');		
updateWord.innerHTML	=	word;
#EBOOKCRAFT JS WORKSHOP

@christinatruong
2b. & 2c. Project Exercise
function	select(word)	{	
		//	Grab	the	blank	text	HTML	container	
var	updateWord	=	document.querySelector('.word');	
		//	Replace	the	container's	content	with	the	selected	word	
updateWord.innerHTML	=	word;	
}
Update the function.
Further reading: MDN innerHTML
Part 4: Add CSS
Animations
#EBOOKCRAFT JS WORKSHOP

@christinatruong
#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>
var	animation	=	document.querySelector('#wrapper');
#EBOOKCRAFT JS WORKSHOP

@christinatruong
3b. Project Exercise
3. 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()
#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.
var	animation	=	document.querySelector('#wrapper');	
animation.setAttribute('class',	word);	
<div id="wrapper" class="selected-option"></div>
#EBOOKCRAFT JS WORKSHOP

@christinatruong
3a. & 3b. Project Exercise
function	select(word)	{	
		//	Grab	the	blank	text	HTML	container	
		var	updateWord	=	document.querySelector('.word');	
		//	Replace	the	container's	content	with	the	selected	word	
		updateWord.innerHTML	=	word;	
		//	Grabs	the	animation	wrapper	div	
		var	animation	=	document.querySelector('#wrapper');	
		//	Adds	a	class	attribute	with	the	selected	option	value	
		animation.setAttribute('class',	word);	
}
Update the function.
It works!
Sorta…
#EBOOKCRAFT JS WORKSHOP

@christinatruong
#EBOOKCRAFT JS WORKSHOP

@christinatruong
HTML & JavaScript
It 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.
#EBOOKCRAFT JS WORKSHOP

@christinatruong
HTML
This 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>
#EBOOKCRAFT JS WORKSHOP

@christinatruong
CSS
The 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;
}
#EBOOKCRAFT JS WORKSHOP

@christinatruong
JavaScript & innerHTML
var	animation	=	document.querySelector('#wrapper');	
animation.innerHTML	=	'<span	class="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
#EBOOKCRAFT JS WORKSHOP

@christinatruong
Concatenation
If you use the + operator with numerical values, it will
add the values.
var	number	=	2	+	2;	
//	result:	4	
var	number	=	3;	
var	addIt	=	number	+	5;	
//	result:	8
#EBOOKCRAFT JS WORKSHOP

@christinatruong
Concatenation
If you use the + operator with at least one string, it
will combine the outputs.
var	numberAndString	=	"3"	+	5;	
//	result:	35	
var	example	=	"Hello.	"	+	"My	name	is	Christina.";	
//	Result:	Hello.	My	name	is	Christina;	
var	example	=	"Hello.	";	
example	+=	"My	name	is	Christina.";	
//	Result:	Hello.	My	name	is	Christina;
Further reading: String Concatenation and String Operators
#EBOOKCRAFT JS WORKSHOP

@christinatruong
Add Multiple Elements
Use a for loop to generate multiple elements.
for	(var	i	=	0;	i	<	5;	i++)	{	
		animation.innerHTML	+=	'<span	class="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
#EBOOKCRAFT JS WORKSHOP

@christinatruong
Add Multiple Elements
for	(var	i	=	0;	i	<	5;	i++)	{	
		animation.innerHTML	+=	'<span	class="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>
#EBOOKCRAFT JS WORKSHOP

@christinatruong
Add Multiple Elements
Every 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	(var	i	=	0;	i	<	5;	i++)	{	
		animation.innerHTML	+=	'<span	class="animation"	style="top:0px;	
																										left:400px;"></span>';	
}
#EBOOKCRAFT JS WORKSHOP

@christinatruong
Randomize the CSS Position
Generate random values for the top and left CSS
properties using the function below.


//	Generate	a	random	integer	between	two	values	
function	getRandomInt(min,	max)	{	
		min	=	Math.ceil(min);	
		max	=	Math.floor(max);	
		return	Math.floor(Math.random()	*	(max	-	min))	+	min;	
}
Further Reading: MDN - Math.random()
#EBOOKCRAFT JS WORKSHOP

@christinatruong
Randomize the CSS Position
Use variables as a placeholder to generate random top and bottom
values for each <span> element.


//	Generate	random	values	between	two	values	
var	topValue	=	getRandomInt(0,600);	
var	leftValue	=	getRandomInt(0,1200);	
The variables and HTML must be concatenated because we are
mixing strings and variables.
animation.innerHTML	+=	'<span	class="animation"	style="top:'	
+	topValue	+	'px;	left:'	+	leftValue	+	'px;"></span>'
#EBOOKCRAFT JS WORKSHOP

@christinatruong
Final Update
function	select(word)	{	
		//	Grab	the	blank	text	HTML	container	
		var	updateWord	=	document.querySelector('.word');	
		//	Replace	the	container's	content	with	the	selected	word	
		updateWord.innerHTML	=	word;	
		//	Grabs	the	animation	wrapper	div	
		var	animation	=	document.querySelector('#wrapper');	
		//	Adds	a	class	attribute	with	the	selected	option	value	
		animation.setAttribute('class',	word);	
		//	Resets	and	removes	any	previously	added	span	element.	
		animation.innerHTML	=	"";	
		//	Adds	multiple	animation	elements	
		for	(var	i	=	0;	i	<	5;	i++)	{	
				var	topValue	=	getRandomInt(0,600);	
				var	leftValue	=	getRandomInt(0,1200);	
			animation.innerHTML	+=	'<span	class="animation"	style="top:'	+	topValue	+	'px;		
																											left:'	+	leftValue	+	'px;"></span>'	
		}	
}
Bonus!
#EBOOKCRAFT JS WORKSHOP

@christinatruong
#EBOOKCRAFT JS WORKSHOP

@christinatruong
if / else Conditionals
To make the snow appear to "fall" at different starting
points, use a negative margin value.
Use if/else	to 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);			
}
#EBOOKCRAFT JS WORKSHOP

@christinatruong
Update the Loop
for	(var	i	=	0;	i	<	5;	i++)	{	
var	topValue;	
var	leftValue;	
if	(word	===	"snowy"){	
		topValue	=	getRandomInt(-1000,0);	
	leftValue	=	getRandomInt(0,1200);			
}	else	{	
		topValue	=	getRandomInt(1,600);	
		leftValue	=	getRandomInt(1,1200);			
}	
animation.innerHTML	+=	'<span	class="animation"	style="top:'		
							+	topValue	+	'px;	left:'	+	leftValue	+	'px;"></span>'	
}
You did it!
#EBOOKCRAFT JS WORKSHOP

@christinatruong
#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

JavaScript and EPUB: Making interactive ebooks - Christina Truong - ebookcraft 2017

  • 1.
    JAVASCRIPT AND EPUB: MakingInteractive Ebooks christinatruong.com
 @christinatruong ebookcraft - March 22, 2017
  • 2.
    Slides (PDF) bit.ly/ebookcraft-slides Onlineeditor codepen.io #EBOOKCRAFT JS WORKSHOP
 @christinatruong
  • 3.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong HTMLdefines the content. CSS adds presentational styles. JavaScript adds interaction.
  • 4.
  • 5.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong JavaScriptand EPUB3 Adding 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
  • 6.
  • 7.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong Whatis JavaScript? • Programming language • Different programming languages have different syntaxes • Programs, or scripts, are a set of instructions for the computer to execute
  • 8.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong Writinga Program 1. 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
  • 9.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong JavaScriptand Programming Programming 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.
  • 10.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong Todayyou will learn about… • functions • variables • objects • for loop • conditionals • concatenation
  • 11.
  • 12.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong ProjectPlan 1. 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
  • 13.
    Part 1: Createa set of instructions #EBOOKCRAFT JS WORKSHOP
 @christinatruong
  • 14.
    #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() //creates a dialogue box Further reading: Mozilla Developer Network (MDN) - prompt()
  • 15.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong CreatingYour 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 function myFunction(){ // instructions here } myFunction();
  • 16.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong Functionsand Arguments Arguments can be used to pass data into a function. Reuse the function with different arguments. //creates an empty dialogue box
 prompt() //creates a dialogue box with a message.
 prompt("What is your name?")
 prompt("What is the date?")
  • 17.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong Statements Statementsare instructions given to the computer. Single line statements end with a semi-colon to indicate the end of the instruction. prompt(); 
 prompt("What is your name?");
  • 18.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong Blockstatements group statements into code blocks and are enclosed by a pair of curly brackets { }. myFunction(){ prompt("What is your name?"); } Block Statements Single line statements must end in a semi-colon. Block statements do not need to end in a semi-colon.
  • 19.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong Leavecomments to organize your code or leave notes for yourself and others. Comments // Defining the function function myFunction(){ console.log("hello"); } // Calling the function myFunction();
  • 20.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong Thereare two styles of writing comments. Comments // This is a single line comment. // You can use many single line comments. // Just add the double forward slash to every line. /* This is another way to write multi-line comments. Any characters can be added within this block. */
  • 21.
    Exercise time! #EBOOKCRAFT JSWORKSHOP
 @christinatruong
  • 22.
    1. Open anew pen in codepen.io: Create > New Pen 1 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
  • 23.
    3. (Optional) ChangeView to move the HTML, CSS and JS panels. 1 2 #EBOOKCRAFT JS WORKSHOP
 @christinatruong
  • 24.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong Exercise Inyour editor, add the prompt() function. Try it with and without an argument to compare the difference. prompt();
 prompt('What is your name?'); Important! 
 When passing an argument, use single or double quotes. 
 (More on this later).
  • 25.
    Where did it go? #EBOOKCRAFTJS WORKSHOP
 @christinatruong
  • 26.
    Part 2: Storingdata #EBOOKCRAFT JS WORKSHOP
 @christinatruong
  • 27.
    #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 Example
 Use a variable to store a customer's name. 
 Then, use the stored data to output the customer's name into a confirmation email.
  • 28.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong Declaringa 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 var firstname;
 firstname = "Christina"; • Variables can also be declared & assigned in one line. var firstname = "Christina"; Further reading: Understanding let and const
  • 29.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong NamingConventions • Variables cannot contain spaces, use camelCase • JavaScript is case-sensitive • Use descriptive names • Cannot start with a number var submitButton; // Descriptive var submitBtn; // Common abbreviation for "button" var sb; // Not descriptive
  • 30.
    #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
  • 31.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong TheConsole A 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
  • 32.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong Theconsole 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
  • 33.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong BrowserConsole 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
  • 34.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong Testingin the Console Use the following method to log information and data to the console. //syntax console.log(argument); 
 //example var firstname = "Christina"; console.log(firstname);
  • 35.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong Exercise Usea variable to store the prompt() input data.
 Use console.log() to output the answer into the console. // option 1 var name = prompt("What is your name?"); console.log(name); // option 2 var question = "What is your name?"; var answer = prompt(question); console.log(answer);
  • 36.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong Whitespace Refersto blank or space characters, tabs & line breaks. JavaScript ignores whitespace in some instances. var name="Christina Truong"; // will both display the same
 var name = "Christina Truong"; Whitespace matters when used in a string or using keyword. var name = "ChristinaTruong"; // Will show with no space
 varname = "Christina Truong"; // not valid
  • 37.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong ProjectStarter Files: bit.ly/ebookcraft-start (codepen)
  • 38.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong ProjectSetup Starter 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
  • 39.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong 1a.Project Exercise 1. 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>
  • 40.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong 2a.Project Exercise 2. Update the sentence with the selected word (a) Store the selected option • Create a function to execute when the button is clicked function select(){ //instructions here } • Pass in the value of the selected option & output it to the console function select(word) { console.log(word); } • Call this function to execute these steps. select('starry'); or select('snowy');
  • 41.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong 2a.Project Exercise Add the function to your projects. function select(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>
  • 42.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong 2b& 2c. Project Exercise 2. 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: function select(word) { // Grab the blank text HTML container // Replace the container's content with the selected word }
  • 43.
    Part 3: Manipulating HTMLObjects #EBOOKCRAFT JS WORKSHOP
 @christinatruong
  • 44.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong TheDocument Object Model Web pages — the browser document, is made up of many blocks. Each HTML element is an object.
  • 45.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong Variablesvs Objects A variable holds one value. Access the value using the name. var food = "pizza"; console.log(food);// returns pizza An object holds a collection of values. Assign and access the property values using dot notation. var pizza = {}; pizza.crust = "thin"; pizza.meat = "pepperoni"; pizza.veg = "mushrooms"; console.log(pizza.crust);// returns thin
  • 46.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong Objects,Functions and Methods Methods are just like functions, except they are applied to objects. Functions run on their own. // function alert("Hello!"); // method attached to an object document.write("Hello!");
  • 47.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong querySelector() Whenapplied 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.
  • 48.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong querySelector() Usea variable to hold the selected HTML element (the container for the word to be updated). function select(word) { // Grab the blank text HTML container var updateWord = document.querySelector('.word'); }
  • 49.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong innerHTML innerHTMLis 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. var updateWord = document.querySelector('.word'); updateWord.innerHTML = word;
  • 50.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong 2b.& 2c. Project Exercise function select(word) { // Grab the blank text HTML container var updateWord = document.querySelector('.word'); // Replace the container's content with the selected word updateWord.innerHTML = word; } Update the function. Further reading: MDN innerHTML
  • 51.
    Part 4: AddCSS Animations #EBOOKCRAFT JS WORKSHOP
 @christinatruong
  • 52.
    #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> var animation = document.querySelector('#wrapper');
  • 53.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong 3b.Project Exercise 3. 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()
  • 54.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong setAttribute() Ifthe attribute already exists in the selected element, the value is updated; otherwise a new attribute is added with the specified name and value. var animation = document.querySelector('#wrapper'); animation.setAttribute('class', word); <div id="wrapper" class="selected-option"></div>
  • 55.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong 3a.& 3b. Project Exercise function select(word) { // Grab the blank text HTML container var updateWord = document.querySelector('.word'); // Replace the container's content with the selected word updateWord.innerHTML = word; // Grabs the animation wrapper div var animation = document.querySelector('#wrapper'); // Adds a class attribute with the selected option value animation.setAttribute('class', word); } Update the function.
  • 56.
    It works! Sorta… #EBOOKCRAFT JSWORKSHOP
 @christinatruong
  • 57.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong HTML& JavaScript It 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.
  • 58.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong HTML Thisis 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>
  • 59.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong CSS Thetop 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; }
  • 60.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong JavaScript& innerHTML var animation = document.querySelector('#wrapper'); animation.innerHTML = '<span class="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>
  • 61.
    We're not done yet! #EBOOKCRAFTJS WORKSHOP
 @christinatruong
  • 62.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong Concatenation Ifyou use the + operator with numerical values, it will add the values. var number = 2 + 2; // result: 4 var number = 3; var addIt = number + 5; // result: 8
  • 63.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong Concatenation Ifyou use the + operator with at least one string, it will combine the outputs. var numberAndString = "3" + 5; // result: 35 var example = "Hello. " + "My name is Christina."; // Result: Hello. My name is Christina; var example = "Hello. "; example += "My name is Christina."; // Result: Hello. My name is Christina; Further reading: String Concatenation and String Operators
  • 64.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong AddMultiple Elements Use a for loop to generate multiple elements. for (var i = 0; i < 5; i++) { animation.innerHTML += '<span class="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
  • 65.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong AddMultiple Elements for (var i = 0; i < 5; i++) { animation.innerHTML += '<span class="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>
  • 66.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong AddMultiple Elements Every 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 (var i = 0; i < 5; i++) { animation.innerHTML += '<span class="animation" style="top:0px; left:400px;"></span>'; }
  • 67.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong Randomizethe CSS Position Generate random values for the top and left CSS properties using the function below. 
 // Generate a random integer between two values function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; } Further Reading: MDN - Math.random()
  • 68.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong Randomizethe CSS Position Use variables as a placeholder to generate random top and bottom values for each <span> element. 
 // Generate random values between two values var topValue = getRandomInt(0,600); var leftValue = getRandomInt(0,1200); The variables and HTML must be concatenated because we are mixing strings and variables. animation.innerHTML += '<span class="animation" style="top:' + topValue + 'px; left:' + leftValue + 'px;"></span>'
  • 69.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong FinalUpdate function select(word) { // Grab the blank text HTML container var updateWord = document.querySelector('.word'); // Replace the container's content with the selected word updateWord.innerHTML = word; // Grabs the animation wrapper div var animation = document.querySelector('#wrapper'); // Adds a class attribute with the selected option value animation.setAttribute('class', word); // Resets and removes any previously added span element. animation.innerHTML = ""; // Adds multiple animation elements for (var i = 0; i < 5; i++) { var topValue = getRandomInt(0,600); var leftValue = getRandomInt(0,1200); animation.innerHTML += '<span class="animation" style="top:' + topValue + 'px; left:' + leftValue + 'px;"></span>' } }
  • 70.
  • 71.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong if/ else Conditionals To make the snow appear to "fall" at different starting points, use a negative margin value. Use if/else to 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); }
  • 72.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong Updatethe Loop for (var i = 0; i < 5; i++) { var topValue; var leftValue; if (word === "snowy"){ topValue = getRandomInt(-1000,0); leftValue = getRandomInt(0,1200); } else { topValue = getRandomInt(1,600); leftValue = getRandomInt(1,1200); } animation.innerHTML += '<span class="animation" style="top:' + topValue + 'px; left:' + leftValue + 'px;"></span>' }
  • 73.
    You did it! #EBOOKCRAFTJS WORKSHOP
 @christinatruong
  • 74.
    #EBOOKCRAFT JS WORKSHOP
 @christinatruong ExtraResources • idpf: EPUB Content Documents - Scripting • idpf: JavaScript epubReadingSystem Object • javascript.com - Tutorials • eloquentjavascript.net - online book including interactive demos
  • 75.
    Thank you! #EBOOKCRAFT JSWORKSHOP
 @christinatruong