Last week you learned how to use JS to connect your app to an online database, upload data (aka write) and download data (aka write).
Today we'll begin with a JS quiz!
We'll also introduce two magic words that you'll sprinkle across HTML, CSS and JS: class and id!
Then you'll start using jQuery, one of the most popular JS libraries (that is, collections of code to accomplish common programming tasks, generally free) to display data from Firebase in your app's interface.
But first, a little recap!
-
Java and JavaScript are the same thing.
- true
- false
-
What is wrong with this JS code?
var userName = 'Jo";
-
What is wrong with this JS code?
var person = { }; person name = 'Jo';
-
What will this JS code produce?
person.drink = function ( beverage ) { alert ( "I am drinking " + beverage + "!" ); } person.drink( "coconut water" );
-
What will this JS code produce?
person.whisper = function ( message ) { console.log ("Sshhh... " + message ); } person.whisper( "Keep calm and code on" );
-
What will this JS code produce?
function areYouAnAdult ( age ) { var answer; if (age < 18) { answer = "no"; } else { answer = "yes"; } return answer; } areYouAnAdult( 18 );
-
Where is better to put JavaScript
<script src="example.js"></script>in your HTML?-
inside the
head... <head> ... <script src="example.js"></script> </head> <body> ...
-
at the end of the
body... <body> ... <script src="example.js"></script> </body>
-
Go to thimble.mozilla.org and log in. Then open your project from last week.
In
app.jscan you spot variables, functions and objects?
Translating JS into your own plain-English comments will help you make sense of your code. Even after years of JS development (and despite English not being Matteo's mother tongue) we find reading English much easier than JS :)
In JS you can write a comment using double forward-slash // (without spaces between the two slashes)
// this is a JavaScript comment
var databaseURL = 'https://codeyourapp.firebaseio.com/';or using /* ... */ if you want to comment out multiple lines at once (useful sometimes)
/*
person.whisper = function ( message ) {
console.log ("Sshhh... " + message );
}
person.whisper( "Keep calm and code on" );
*/Read through your JS code line by line, and write comments so that you have an English translation of the JS you wrote.
One of the most common beginner mistakes is missing brackets.
How do you make it easier to read your code and spot such mistakes?
Compare the two examples of HTML below. Which is easier to read?
Example A:
<body>
<h1>Short title</h1>
<p>In this example, we have a relatively long paragraph. With longer content inside our element, we want to make it as easy as possible to differentiate between our code and our content. If we don't indent our code, you can see how it becomes harder to spot where our p element starts and where it ends.</p>
<p>Indentation is also useful to spot errors in our code such as missing brackets or unclosed tags.</p><p>A good practice is to have both the opening and closing tags of the element aligned, with the inner content indented on a new line.</p></body>Example B:
<body>
<h1>Short title</h1>
<p>
In this example, we have a relatively long paragraph. With longer content inside our element, we want to make it as easy as possible to differentiate between our code and our content. If we don't indent our code, you can see how it becomes harder to spot where our p element starts and where it ends.
</p>
<p>
Indentation is also useful to spot errors in our code such as missing brackets or unclosed tags.
</p>
<p>
A good practice is to have both the opening and closing tags of the element aligned, with the content indented on a new line.
</p>
</body> The second example uses indentation. That means giving your code a consistent visual structure by pushing lines left or right.
Indenting your code makes it easier to:
- differentiate between code and text/content
- understand how code is structured, as nested elements are also visually nested
- spot if you've missed something, as start
<p>and end</p>are visually aligned
Open
index.htmlof your app.
Starting from the top of the document, select one or more lines of code, then use cmd + ] to move your selection to the right, or cmd + [ to move your selection to the left.
Go through all your HTML until it's tidy and legible.
In CSS, the best practices are much debated. On the whole, it's essential to open and close your brackets {}, then inside them on a new line, place your indented styles like so:
h1 {
text-align: center;
}Or so:
h1
{
text-align: center;
}How NOT to do it:
h1{text-align: center;}If your code is not indented, it can be really easy to miss out a bracket or semi-colon, then spend half an hour trying to figure out why the page is broken!
Open
style.cssof your app.
Starting from the top of the document, select one or more lines of code, then use cmd + ] to move your selection to the right, or cmd + [ to move your selection to the left.
Go through all your CSS until it's tidy and legible.
So far in your CSS experiments you changed the look & feel of the different parts of your HTML.
You selected headings using h1, paragraphs with p, buttons with button and dropdowns with select.
In your CSS you may have something like this:
p
{
color: grey;
font-size: 20px;
text-align: center;
/* this is a CSS comment */
}The block of CSS code inside curly brackets {} applies to every paragraph p in your HTML.
Targeting your elements by simply using their name (like p, h1 and so on) has worked fine up until now.
But...
- What if you want to apply different styles to different paragraphs
p? - What if some of the same styles are applied to several elements, and you find you're repeating yourself?
In HTML you can use class to classify your elements, and in CSS you can target those elements to give them different styles.
In your HTML opening tags, add in class=" " with your own class names inside the " ". You can add as many classes as you want, separated by a space:
<p class="textCentred specialText" > Swap skills or time with people in your area </p>
<p class="textCentred" > Just pick an option from the dropdown to get started </p>Above, there are two classes added to the first p - textCentred and specialText.
You could call them whatever you like: class names are entirely up to you. However, it makes sense to give them descriptive short names.
In CSS, target these classes using a dot . before the class name, like so:
.textCentred
{
text-align: center;
}
.specialText
{
color: pink;
}Now you can use textCentred to centre other elements instead of having to create or add the style text-align: center; to every single element you want centred.
<h1 class="textCentred">I'd like someone to...</h1>Likewise the second class specialText can be used to turn the text inside any element pink.
Classes are useful for shared rules.
Whilst classes are used for shared rules, sometimes it's important to get super, super specific!
Adding an id is like giving an element a name of its own.
For example, IF animal were an HTML element (stay with us here...) you could write something like this:
<animal class="mammal dog" id="Sparky" > </animal>
<animal class="mammal cat" id="Bruno" > </animal>As you can see, the two animals share a class mammal and have other, more specific classes: dog and cat. Their unique name is inside the id attribute.
Giving an element a unique id allows you to style it differently from any other instances of the same element on the page. It is important that no two elements on the same HTML have the same id. In other words, id must be unique.
<p class="textCentred" id="instructions" > Just pick an option from the dropdown to get started </p>In CSS, target ids using a hash # before the id name, like so:
#instructions
{
color: black;
}Ids are the most powerful CSS selectors: the styles you apply to them override all other styles.
Your app prototype will have two sections:
- Home section with dropdown menu,
Findbutton and search results
- Details section for each item in the search results
Let's finish off the home section interface.
You've already created two separate sections inside your HTML. One of those sections contains the dropdown, the find button and the results list with placeholder content inside.
...
<body>
<section>
<h1>I'd like someone to...<h1>
<select>
<option>Bake a cake</option>
<option>Move my furniture</option>
<option>Keep my pet</option>
</select>
<!--etc etc...-->
</section>
</body>Give the first
section(which contains thedropdownmenu) anid="home"
Underneath the <section id="home"> ... </section> you should already have an empty <section></section>.
Give this
sectionanid="details"and make some space inbetween the opening and closing tag.
Inside
<section id="details"> ... </section>create a new<div id="person"></div>. This will be the details screen, where a selected person's profile will be displayed.
In the #home section you created an unordered list ul with list items inside li. Within those you put an image img, a heading 2 h2 and a paragraph p.
We're going to use that img, h2 and p in #details.
Copy the
img,h2andpfrom theliin#homeand paste them inside<div id="person"> </div>like so
Your users may want to move back and forth between #home and #details. For that you'll need a Back button!
Add in
<a id="back">Back</a>above<div id="person">
Your users will also need a way to contact the person. Add in a contact button inside your #person: <a class="contactButton">Contact Aimee</a>
Your
<section id="details"></section>will look something like this:
<section id="details">
<a id="back">Back</a>
<div id="person">
<img src="https://avatars3.githubusercontent.com/u/9767977">
<h2>
Aimee
</h2>
<p>
I like code and cake
</p>
<a class="contactButton">Contact Aimee</a>
</div>
</section>How does JS know which data to ask from the database, after a user has picked an option from the dropdown?
To let JS know which data to look for, we can add a little bit of information to each option in our HTML dropdown.
Scroll back up to your
selectdropdown menu in#home. In each openingoptiontag add invalue=" "
Bake a cake Move my furniture Keep my pet ```
The value attribute will contain the property which relates to the selected option - the exact spelling you use in your database.
For example, if the user selects Bake a cake, the property which matches that is bakingSkills.
Open your Firebase database at codeyourapp.firebaseio.com and take a look at the data you've stored in there.
Copy property names from the database and paste them in the relevant value slot in your HTML. Make sure to double-check for the exact property names, otherwise your JS code will not work!
Bake a cake Move my furniture Keep my pet ```
Aka Don't reinvent the wheel.
Code libraries are collections of pre-written functions which you use to avoid re-writing the same code over and over again.
One of the first libraries we recommend you get familiar with is jsQuirrel... :squirrel:
The first version of jQuery was written in 2006 by a guy called John Resig. He noticed how he was using the same JS functions over and over, across different projects. So he put together a JS toolkit, aka a library, and since it was working well for him, he decided to share it with the NYC Web dev community, and then with the rest of the WWW.
Over the years, jQuery has been peer-reviewed and enhanced by thousands of developers. It is currently the the most popular JavaScript library on the Web, with ~78% of the top 1 million websites using it!
And it's FREE!
John made a point of listening carefully to the community and incorporating feedback from those interactions which made both the code and documentation better.
jQuery makes it easy to select HTML elements and manipulate them, for example hiding, showing, moving around and changing the content of a bunch of HTML elements.
jQuery uses CSS-like selectors.
For example, if you want to select all h1 elements in your HTML, you can do it like this
jQuery('h1');
// notice the lowercase j and capital Q in jQuery...which is the equivalent of telling your browser to select all h1 elements in the HTML.
You can then apply functions that manipulate those selected elements.
For example, if you want to hide all h1 elements in your HTML, you can do it like this
jQuery('h1').hide();So to recap:
- Select
- Manipulate
It's common practice to store a jQuery selection in a variable, and then use that variable throughout your code. That way you don't have to select the same HTML elements over and over again.
var h1 = jQuery('h1');
h1.hide();
h1.fadeIn();There's a saying that goes like this:
A good programmer is a lazy programmer.
In practical terms, it means that programmers really like their shortcuts.
There's a shortcut for jQuery too, and it's $
$('h1') achieves the same as jQuery('h1') and it saves you 5 key strokes! :squirrel:
This is what makes programming languages (like JS) so much more powerful than markup languages (like HTML).
Programming has something to do with the future: you define instructions and behaviour that will happen in the future, if and when something specific happens.
For example, you may want to hide an element when you click on a button. Using jQuery, you can do it like this
// select the button element(s)
var button = $('button');
// select the h1 element(s)
var h1 = $('h1');
// when someone clicks the button, hide the h1
button.click( function ()
{
h1.hide();
});We created a handy document with snippets of code for you to copy-paste: bit.ly/copyPasteCodeYourApp
Go to bit.ly/copyPasteCodeYourApp and copy the following code (you can find it under Day 4):
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
> Open `index.html`.
> Just before the **end** of the `body` paste the jQuery `script` like this
> ```html
...
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<!-- Make sure jQuery is loaded before app.js-->
<script src="app.js"></script>
</body>
</html>
Once jQuery is included, we can check if it's ready to for us to use.
Open the Console cmd + alt + J and then type in jQuery and press Enter.
If the Console doesn't spit out a red error, you're good to go!
When people open the app, we don't need them to see details about a person. Later we will write some JS code to display that section when people click on a result, but for now we want to hide that part of the HTML.
At the bottom of
app.jswrite
$('#details').hide();

The line above does two things:
1. `$('#details')`: **select** the element with `id="details"`
* Perform the `hide()` function on that selection
### 3. When someone clicks on the `Find` button, what happens?
> Go to [bit.ly/copyPasteCodeYourApp](https://bit.ly/copyPasteCodeYourApp) and copy the following code (you can find it under Day 4):
> ```javascript
$('button').click( function() {
// get user input
var selectedOption = $('select').val(); // this is jQuery val()
// filter people by user selection
var resultsList = filterAndSortList(peopleList, selectedOption);
console.log(resultsList);
// and show the results
showList(resultsList);
})
Let's break that code down.
First the outer shell:
$('button').click( function() {
...
...
})$('button')selects theFindbutton..click( function() { ... })says when the user clicks the selected element, call this function. In our case, when the user clicksFind, perform this function.
Now inside the function...
What option did the user pick?
// get user input
var selectedOption = $('select').val(); // this is jQuery val(), not Firebase val()- Create a
varnamedselectedOption
$('select'): select theselect(HTML for dropdown) with jQuery$- Get the currently selected value (for example the
likesPets) using the jQuery function.val() - Save that value in
selectedOption
Pick people according to the selected option
// filter people by user selection
var resultsList = filterAndSortList(peopleList, selectedOption);- Create a
varnamedresultsList
- Use the function
filterAndSortListto filter and sortpeopleList(the list with all the people) so that it matches the user 's selection (selectedOption) - Store the filtered people in
resultsList
Create a new file in your Thimble project, call it
filter.js(or whatever you like) and then inindex.htmluse ascriptto loadfilter.jsjust before the one which loadsapp.js.
...
<script src="filter.js"></script>
<script src="app.js"></script>
In
filter.jspaste the whole JS code from github.com/CodeAndCake/AppsFromScratch/blob/v4/demo-app/js/filter.js (link also in the copy-paste GDoc).
Display the results
showList(resultsList);In the line above we are using the function showList to spit out the results in the HTML interface.
Create a new file in your Thimble project, call it
show.js(or whatever you like) and then inindex.htmluse ascriptto loadshow.jsjust before the one which loadsapp.js.
...
<script src="filter.js"></script>
<script src="show.js"></script>
<script src="app.js"></script>
In
show.jspaste the whole JS code from github.com/CodeAndCake/AppsFromScratch/blob/v4/demo-app/js/show.js (link also in the copy-paste GDoc).
See if you can integrate the code below (you can copy it from the copy-paste GDoc) in your
app.js.
$('#back').click( function(){
### License
[](http://creativecommons.org/licenses/by-nc-sa/4.0)
This work is licensed under a [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License ](http://creativecommons.org/licenses/by-nc-sa/4.0)

