Pixels and emsGreat work! We'll do more with colors as you learn
more CSS.When we've asked you to adjust font size, we've specified
that the unit you should use is px (for "pixels"), like so:p {
font-size: 10px;}A pixel is a dot on your computer screen.
Specifying font sizes in pixels is great when you want the user to
see exactly on their screen what you designed on yours, though it
assumes your screens are of similar size.What if the user is using
a screen that's a very different size from yours, though (like a
smartphone screen)? Enter ems. (Don't confuse these with the tags
we use for emphasis!)The font-size unit em is a relative measure:
one em is equal to the default font size on whatever screen the
user is using. That makes it great for smartphone screens, since it
doesn't try to tell the smartphone exactly how big to make a font:
it just says, "Hey, 1em is the font size that you normally use, so
2em is twice as big and 0.5em is half that size!"Check it out:
we've set three different paragraphs to the font-sizes 1em, 0.5em,
and 2em. For now, use whichever unit (px or em) you're more
comfortable withwe just wanted to show you em now so you're not
surprised when you see it later.
A font of knowledgeWe've also asked you to change the
font-family of certain elements using CSS. You've seen us use the
fonts Verdana, Courier, and Garamond. But how many fonts does CSS
know?The answer is: it depends. Most computers will understand
popular fonts like Verdana, Courier, and Garamond, but each
individual computer has different fonts installed on it. The good
news is that CSS has some built-in defaults meant to ensure your
users see what you intend. They are:serif: A font with little
decorative bits on the ends of the strokes that make up letters. Do
a search on "serif" to see what we mean.sans-serif: A plain-looking
font, like this one. It doesn't have the little doohickies on the
ends of letters like a serif font does.cursive: A scripty font! It
looks like cursive writing.We'll show you how to import your own
fonts in a later course! This will help make sure the person
viewing your page has all the fonts you want them to have.
Backup valuesYou don't have to jump straight to a default value
like cursive or sans-serif: you can tell CSS to try several, going
from one to the next if the one you want isn't available.For
example, if you write:p { font-family: Tahoma, Verdana,
sans-serif;}CSS will first try to apply Tahoma to your paragraphs.
If the user's computer doesn't have that font, it will try Verdana
next, and if that doesn't work, it will show a default sans-serif
font.
Can you swing it?Good work! Let's try something a little more
involved.Remember, you can reach an element that is a child of
another element like this:div div p { /* Some CSS */ }where in this
case, we'd be grabbing any that is nested somewhere inside a that
is nested somewhere inside another . If you want to grab direct
childrenthat is, an element that is directly nested inside another
element, with no elements in betweenyou can use the > symbol,
like so:div > p { /* Some CSS */ }This only grabs s that are
nested directly inside of s; it won't grab any paragraphs that are,
say, nested inside lists that are in turn nested inside s.
Even finer controlYou've learned about class selectors. Now it's
time to learn about pseudo-class selectors.A pseudo-class selector
is a way of accessing HTML items that aren't part of the document
tree (remember the tree structure we talked about earlier?). For
instance, it's very easy to see where a link is in the tree. But
where would you find information about whether a link had been
clicked on or not? It isn't there!Pseudo-class selectors let us
style these kinds of changes in our HTML document. For example, we
saw we could change a link's text-decoration property to make it
something other than blue and underlined. Using pseudo selectors,
you can control the appearance of unvisited and visited linkseven
links the user is hovering over but hasn't clicked!The CSS syntax
for pseudo selectors isselector:pseudo-class_selector { property:
value;}It's just that little extra colon (:).
Nth childWell done! You can actually select any child of an
element after the first child with the pseudo-class selector
nth-child; you just add the child's number in parentheses after the
pseudo-class selector. For example,p:nth-child(2) { color:
red;}Would turn every paragraph that is the second child of its
parent element red.The element that is the child goes before
:nth-child; its parent element is the element that contains it.
Taking up spaceCool, right? Each HTML element gets its own box
to live in.As you saw, the outermost box of each element went all
the way across the page. This is why until now, your HTML elements
have been sitting on top of one another: by default, they take up
the full width of the page.We can change all this with the first
positioning property we'll learn: the display property. We'll learn
about four possible values.block: This makes the element a block
box. It won't let anything sit next to it on the page! It takes up
the full width.inline-block: This makes the element a block box,
but will allow other elements to sit next to it on the same
line.inline: This makes the element sit on the same line as another
element, but without formatting it like a block. It only takes up
as much width as it needs (not the whole line).none: This makes the
element and its content disappear from the page entirely!
Sketching it outNow that you understand more about the display
property and the box model, we can delve into the details of how
each individual box behaves.Check out the diagram in the Result tab
(it's the one from the first exercise in this lesson). As you can
see, each box is made of layers. From the outermost to the
innermost:The margin is the space around the element. The larger
the margin, the more space between our element and the elements
around it. We can adjust the margin to move our HTML elements
closer to or farther from each other.The border is the edge of the
element. It's what we've been making visible every time we set the
border property.The padding is the spacing between the content and
the border. We can adjust this value with CSS to move the border
closer to or farther from the content.The content is the actual
"stuff" in the box. If we're talking about a element, the "stuff"
is the text of the paragraph.
MarginLet's start with our margins. Adjusting our margins not
only moves our element relative to other elements on the page, but
also relative to the "walls" of the HTML document.For instance, if
we take an HTML element with a specific width (such as our in the
editor) and set its margin to auto, this tells the document to
automatically put equal left and right margins on our element,
centering it on the page.
To the right!Okay! So we know how our individual elements are
constructed. But how do we determine where they go on the page?One
way is to use floats. When you float an element on the page, you're
telling the webpage: "I'm about to tell you where to put this
element, but you have to put it into the flow of other elements."
This means that if you have several elements all floating, they all
know the others are there and don't land on top of each other.You
can think of the HTML page as sort of like a sea, and floating
elements as boats on it: all the boats have positions on the sea,
and they all see and steer clear of each other.(Some of the
positioning methods we'll learn in upcoming sections can
accidentally drop elements on top of each other.)
Clearing elementsUnfortunately, we sometimes mix large floating
elements with non-floating ones, and elements do end up on top of
each other.See your footer (the blue bit between the two columns)?
It's stuck back there because we haven't told it something very
important: to clear the other elements on the page!If you tell an
element to clear: left, it will immediately move below any floating
elements on the left side of the page; it can also clear elements
on the right. If you tell it to clear: both, it will get out of the
way of elements floating on the left and right!The syntax is what
you're used to:element { clear: /*right, left, or both*/}
Absolute positioningThe first type of positioning is absolute
positioning. When an element is set to position: absolute, it's
then positioned in relation to the first parent element it has that
doesn't have position: static. If there's no such element, the
element with position: absolute gets positioned relative to .To
show you how this works, we've set the #outer div to have absolute
positioning. This means that when you position the #inner div, it
will be relative to #outer. (If #outer had the default positioning
of static, then #inner would get positioned relative to the entire
HTML document.)
Relative positioningGood! Did you notice how the #inner div
moved 20 pixels in from the edge of the #outer div? That's absolute
positioning at work.Relative positioning is more straightforward:
it tells the element to move relative to where it would have landed
if it just had the default static positioning.If you give an
element relative positioning and tell it to have a margin-top of
10px, it doesn't move down ten pixels from any particular thingit
moves down ten pixels from where it otherwise would have been.
Fixing your headerGreat work!Now it's time to fix your
headerliterallyso it stays put on the page as people reading your
resume scroll down.If you read the first exercise's CSS carefully,
you'll see we've snuck in a little trick for you: the z-index
property. You can think of the z-index as a measure of importance:
the higher an element's z-index, the higher it will be "stacked" on
the page. Giving your header a z-index of 1 while not giving any of
the other elements a z-index ensures that your header will sit "on
top of" your other elements and won't get stuck behind them.
JavaScript
Interactive JavaScriptWhat we just saw was a fun example of how
JavaScript can be interactive. Try it yourself!Examples:confirm("I
feel awesome!");confirm("I am ready to go.");These boxes can be
used on websites to confirm things with users. You've probably seen
them pop up when you try to delete important things or leave a
website with unsaved changes.
What is programming?Programming is like writing a list of
instructions to the computer so it can do cool stuff with your
information.Programs can't yet make your bed, but they can do math,
keep track of your bank account, or send a message to a friend.To
do any of these actions, the program needs an input. You can ask
for input with a prompt.Examples:1. prompt("What is your name?");2.
prompt("What is Ubuntu?");
Data Types I & II: Numbers & StringsData comes in
various types. You have used two already!a. numbers are quantities,
just like you're used to. You can do math with them.b. strings are
sequences of characters, like the letters a-z, spaces, and even
numbers. These are all strings: "Ryan", "4" and "What is your
name?" Strings are extremely useful as labels, names, and content
for your programs.To make a number in your code, just write a
number as numerals without quotes: 42, 190.12334.To write a string,
surround words with quotes: "What is your name?"
Data Type III: BooleansNice job! Next let's look at booleans. A
boolean is either true or false.For example, comparing two numbers
returns a true or false result: 23 > 10 is true5 < 4 is
false
Using console.logYou may have noticed that the interpreter
doesn't print out every single thing it does. So if we want to know
what it's thinking, we sometimes have to ask it to speak to
us.console.log() will take whatever is inside the parentheses and
log it to the console below your codethat's why it's called
console.log()!This is commonly called printing out.
Math and the moduloLet's meet an interesting symbol called
modulo. When % is placed between two numbers, the computer will
divide the first number by the second, and then return the
remainder of that division.So if we do 23 % 10, we divide 23 by 10
which equals 2 with 3 left over. So 23 % 10 evaluates to 3.More
examples:17 % 5 evaluates to 213 % 7 evaluates to 6
SubstringsWe've learned a few ways to manipulate numbers. What
about manipulating strings?Sometimes you don't want to display the
entire string, just a part of it. For example, in your Gmail inbox,
you can set it to display the first 50 or so characters of each
message so you can preview them. This preview is a substring of the
original string (the entire message).Code:"some word".substring(x,
y) where x is where you start chopping and y is where you finish
chopping the original string.The number part is a little strange.
To select for the "he" in "hello", you would write this:"hello".
substring(0, 2);Each character in a string is numbered starting
from 0, like this:0 1 2 3 4 | | | | | h e l l oThe letter h is in
position 0, the letter e is in position 1, and so on.Therefore if
you start at position 0, and slice right up till position 2, you
are left with just he
VariablesWe have learned how to do a few things now: make
strings, find the length of strings, find what character is in the
nth position, do basic math. Not bad for a day's work!To do more
complex coding, we need a way to 'save' the values from our coding.
We do this by defining a variable with a specific, case-sensitive
name. Once you create (or declare) a variable as having a
particular name, you can then call up that value by typing the
variable name.Code:var varName = data;
Function syntaxA function takes in inputs, does something with
them, and produces an output.Here's an example of a function:var
sayHello = function(name) { console.log('Hello ' + name);}; First
we declare a function using var, and then give it a name sayHello.
The name should begin with a lowercase letter and the convention is
to use lowerCamelCase where each word (except the first) begins
with a capital letter. Then we use the function keyword to tell the
computer that you are making a function The code in the parentheses
is called a parameter. It's a placeholder word that we give a
specific value when we call the function. Click "Stuck? Get a
hint!" for more. Then write your block of reusable code between {
}. Every line of code in this block must end with a ;.You can run
this code by "calling" the function, like
this:sayHello("Emily");Calling this function will print out Hello
Emily.
How does a function work?Let's break down exactly how a computer
thinks when it sees the code for a function.var functionName =
function( ) { // code code code // code code code // (more lines of
code)}; The var keyword declares a variable named functionName. The
keyword function tells the computer that functionName is a function
and not something else. Parameters go in the parentheses. The
computer will look out for it in the code block. The code block is
the reusable code that is between the curly brackets { }. Each line
of code inside { } must end with a semi-colon. The entire function
ends with a semi-colon.To use the function, we call the function by
just typing the function's name, and putting a parameter value
inside parentheses after it. The computer will run the reusable
code with the specific parameter value substituted into the
code.
Return keywordNice job! Now, when we call a function, we don't
always want to just print stuff. Sometimes, we just want it to
return a value. We can then use that value (ie. the output from the
function) in other code. Let's learn about the return keyword, then
we'll see how to use functions with an if / else statement in the
next exercise!The return keyword simply gives the programmer back
the value that comes out of the function. So the function runs, and
when the return keyword is used, the function will immediately stop
running and return the value.Functions with two parametersSo far
we've only looked at functions with one parameter. But often it is
useful to write functions with more than one parameter. For
example, we can have the following function:var areaBox =
function(length, width) { return length * width;};With more than
one parameter, we can create more useful functionsTo call a
function with more than one parameter, just enter a value for each
parameter in the parentheses. For example, areaBox(3,9); would
return the area of a box with a length of 3 and a width of 9.
Global vs Local VariablesLet's talk about an important concept:
scope. Scope can be global or local.Variables defined outside a
function are accessible anywhere once they have been declared. They
are called global variables and their scope is global.For
example:var globalVar = "hello";
var foo = function() { console.log(globalVar); // prints
"hello"}The variable globalVar can be accessed anywhere, even
inside the function foo.Variables defined inside a function are
local variables. They cannot be accessed outside of that
function.For example:var bar = function() { var localVar =
"howdy";}
console.log(localVar); // errorThe variable localVar only exists
inside the function bar. Trying to print localVar outside the
function gives a error.Check out the code in the editor. Until now
you've been using the var keyword without really understanding why.
The var keyword creates a new variable in the current scope. That
means if var is used outside a function, that variable has a global
scope. If var is used inside a function, that variable has a local
scope.Controlling the for loopWe can now control where the for loop
starts and ends. What about controlling what happens in between?The
examples we've looked at have used i = i + 1. This has meant we
have incremented (increased) the variable i by 1 each time.Rules to
learna. A more efficient way to code to increment up by 1 is to
write i++.b. We decrement down by 1 by writing i--.c. We can
increment up by any value by writing i += x, where x is how much we
want to increment up by. e.g., i += 3 counts up by 3s.d. We can
decrement down by any value by writing i -= x. (See the Hint for
more.)e. Be very careful with your syntaxif you write a loop that
can't properly end, it's called an infinite loop. It will crash
your browser!
Meet arraysVariables can store numbers or strings. But so far,
we've only been able to store ONE number or ONE string. Good thing
we have arrays. Arrays:a. store lists of datab. can store different
data types at the same timec. are ordered so the position of each
piece of data is fixedExample:var names =
["Mao","Gandhi","Mandela"];
var sizes = [4, 6, 3, 2, 1, 9];
var mixed = [34, "candy", "blue", 11];Syntax:var arrayName =
[data, data, data];Any time you see data surrounded by [ ], it is
an array.
The 'do' / 'while' loopSometimes you want to make sure your loop
runs at least one time no matter what. When this is the case, you
want a modified while loop called a do/while loop.This loop says:
"Hey! Do this thing one time, then check the condition to see if we
should keep looping." After that, it's just like a normal while:
the loop will continue so long as the condition being evaluated is
true.
If / else if / elseGood! Let's also get some practice in with
else if, as well as learn about a fancy new function: isNaN.If you
call isNaN on something, it checks to see if that thing is not a
number. So:isNaN('berry'); // => trueisNaN(NaN); // =>
trueisNaN(undefined); // => trueisNaN(42); // => falseBe
careful: if you call isNaN on a string that looks like a number,
like '42', JavaScript will try to help by automatically converting
the string '42' to the number 42 and return false (since 42 is a
number).Note that you can't just doisNaN(unicorns);unless you've
already defined the variable unicorns. You can, however,
doisNaN("unicorns"); // => true
Sneak preview: the switch statementAs you might imagine, if you
have a lot of choices you want to cover in a program, it might be
annoying to type else if () ten times. That's why JavaScript has
the switch statement!switch allows you to preset a number of
options (called cases), then check an expression to see if it
matches any of them. If there's a match, the program will perform
the action for the matching case; if there's no match, it can
execute a default option.
Arrays of arraysGood! The next thing to know is that not only
can you put a mixture of types in an array, you can even put other
arrays inside arrays. You can make a two-dimensional array by
nesting arrays one layer deep, like so:var twoDimensional = [[1,
1], [1, 1]];This array is two-dimensional because it has two rows
that each contain two items. If you were to put a new line between
the two rows, you could log a 2D objecta squareto the console, like
so:[1, 1][1, 1]
Nouns and verbs togetherLet's go back to the analogy of computer
languages being like regular spoken languages. In English, you have
nouns (which you can think of as "things") and verbs (which you can
think of as "actions"). Until now, our nouns (data, such as
numbers, strings, or variables) and verbs (functions) have been
separate.No longer!Using objects, we can put our information and
the functions that use that information in the same place.You can
also think of objects as combinations of key-value pairs (like
arrays), only their keys don't have to be numbers like 0, 1, or 2:
they can be strings and variables.
Object syntaxDid you see that? The phonebookEntry object handled
data (a name and a telephone number) as well as a procedure (the
function that printed who it was calling).In that example, we gave
the key name the value 'Oxnard Montalvo' and the key number the
value '(555) 555-5555'. An object is like an array in this way,
except its keys can be variables and strings, not just
numbers.Objects are just collections of information (keys and
values) between curly braces, like this:var myObject = { key:
value, key: value, key: value};
Creating a new objectGreat work! You just created your very
first object.There are two ways to create an object: using object
literal notation (which is what you just did) and using the object
constructor.Literal notation is just creating an object with curly
braces, like this:var myObj = { type: 'fancy', disposition:
'sunny'};
var emptyObj = {};When you use the constructor, the syntax looks
like this:var myObj = new Object();This tells JavaScript: "I want
you to make me a new thing, and I want that thing to be an
Object.You can add keys to your object after you've created it in
two ways:myObj["name"] = "Charlie";myObj.name = "Charlie";Both are
correct, and the second is shorthand for the first. See how this is
sort of similar to arrays?
List 'em all!Great work! Now let's add a couple of functions to
help us go through our contacts.The first function we'll create
will be called list, and it will print out all the entries we have
in our friends object. To do this, we'll want to use a bit of new
syntax: a for/in loop.It looks like this:for (var key in object) {
// Access that key's value // with object[key]}The "key" bit can be
any placeholder name you like. It's sort of like when you put a
placeholder parameter name in a function that takes arguments.
Custom ConstructorsBut this approach of adding in properties one
at a time for every object is tedious! Instead of always using the
boring Object constructor, we can make our own constructors.This
way we can set the properties for an object right when it is
created. So instead of using the Object constructor which is empty
and has no properties, we can make our own constructors which have
properties.To see how this works, look at our Person constructor in
lines 14. This constructor is used to make Person objects. Notice
it uses the keyword this to define the name and age properties and
set them equal to the parameters given.Now we can use this
constructor to make our good friends bob and susan in only one line
each! Look at lines 78: once we have the constructor, it's way
easier to make people because we can include their name and age as
arguments to their respective constructors.
function Person(name,age) { this.name = name; this.age = age;}//
Let's make bob and susan again, using our constructorvar bob = new
Person("Bob Smith", 30);var susan = new Person("Susan Jordan",
25);Arrays of ObjectsRemember that an object is just another type,
like a string or number but more complex. This means that just as
we can make arrays of numbers and strings, we can also make arrays
of objects.Here we have our Person constructor which should look
familiar. We can use this constructor to make an array of Person
objects, similar to how we might make an array of numbers but
filling in people instead.Know ThyselfIn the last exercise, we used
typeof to figure out what type a variable in JavaScript is. Since
we know how to tell objects apart from everything else now, let's
focus on them.You wouldn't know it, but every object in JavaScript
comes with some baggage (stay tuned for more on this!). Part of
this baggage includes a method called hasOwnProperty. This lets us
know if an object has a particular property.
Prototype to the RescueHere we have very similar code as last
time, but there is an important difference. Instead of using
buddy.bark to add the bark method to just the buddy object, we use
Dog.prototype.bark.Click run this time, and both buddy and snoopy
can bark just fine! Snoopy can bark too even though we haven't
added a bark method to that object. How is this so? Because we have
now changed the prototype for the class Dog. This immediately
teaches all Dogs the new method.In general, if you want to add a
method to a class such that all members of the class can use it, we
use the following syntax to extend the
prototype:className.prototype.newMethod =
function() {statements;};
DRY PenguinsCreating a brand new Penguin was nice, but we did
end up reusing a lot of the same code as the Animal class. This
goes against the "DRY" principle of programming: Don't Repeat
Yourself.Inheritance can help us here! A Penguin is an Animal, so
they should have all the same properties and methods as Animal.
Whenever this X is-a Y relationship exists, there's a good chance
that we should be using inheritance.Remember, inheritance lets us
see and use properties and methods from another class. To say that
Penguin inherits from Animal, we need to set Penguin's prototype to
be Animal.Create a new Penguin class. The Penguin constructor can
be more unique than the generic Animal one because all penguins
have 2 legs. Your constructor should only take a name parameter,
and within the constructor itself, set this.numLegs to 2.Set the
Penguin class's prototype to a new instance of Animal by adding
this line after you make the constructor:Penguin.prototype = new
Animal();This means that Penguin inherits properties and methods
from Animal.
Up the Food-I-mean-Prototype ChainA penguin is an animal and an
emperor penguin is a penguin. Are emperor penguins animals too? Of
course!The "prototype chain" in JavaScript knows this as well. If
JavaScript encounters something it can't find in the current
class's methods or properties, it looks up the prototype chain to
see if it's defined in a class that it inherits from. This keeps
going upwards until it stops all the way at the top: the mighty
Object.prototype (more on this later). By default, all classes
inherit directly from Object, unless we change the class's
prototype, like we've been doing for Penguin and Emperor.
Private VariablesGood! But what if an object wants to keep some
information hidden?Just as functions can have local variables which
can only be accessed from within that function, objects can have
private variables. Private variables are pieces of information you
do not want to publicly share, and they can only be directly
accessed from within the class.The Person class has been modified
to have a private variable called bankBalance. Notice that it looks
just like a normal variable, but it is defined inside the
constructor for Person without using this, but instead using var.
This makes bankBalance a private variable.Accessing Private
VariablesAlthough we cannot directly access private variables from
outside the class, there is a way to get around this. We can define
a public method that returns the value of a private variable.
Private MethodsWhy did that code work? An object's private
variables can only be accessed by other methods that are part of
that same object. So, we just used an object's public method to
access a private variable!Methods can also be private within a
class and inaccessible outside of the class. Changing
this.returnBalance from the last exercise to var returnBalance
makes this method private. If you run the program trying to access
the method you get an undefined error this time.The way to access a
private method is similar to accessing a private variable. You must
create a public method for the class that returns the private
method.jQuery
Changing TargetsDon't be intimidated by the amount of code
you're seeingwe'll go through it piece by piece to make sure you
understand it thoroughly.Just like the CSS div refers to the HTML
element , the jQuery 'div' refers to the same HTML element . You
can think of the element name passed to jQuery as identical to the
CSS element, only wrapped in quotes. So, for instance, you could
target anything of class button with$('.button').someActionAs
you'll remember, .button in your CSS file is how you'd target
anything of class="button" in your HTML file.
What is jQuery?jQuery is a library, or set of helpful add-ons,
to the JavaScript programming language. It may seem
counterintuitive to learn how to use a library before learning the
actual language, but there are a few good reasons for this. It
takes a while to become comfortable with JavaScript, and it's
trickier to manipulate HTML elements directly with JavaScript than
with jQuery. In order to help you build awesome websites faster,
we're starting you off with jQuery. jQuery provides a simple
interface for the underlying JavaScript. It's easier for many users
to learn jQuery first, then dive into the nitty-gritty JavaScript
details later.jQuery is much better at giving you immediate, visual
results than regular JavaScript. By the end of this lesson, you'll
have built your own interactive button!
Linking Your HTML and JavaScript FilesGreat! Now we need to link
our HTML page to our jQuery script so our jQuery magic will affect
our HTML.Just like we need a tag to connect our HTML and CSS, we
need a tag to connect our HTML and jQuery. The tag looks like
this:
Note that the tag is not self-closing; it requires a closing
tag.
Getting StartedNext, we'll need to start up our jQuery magic
using the $(document).ready(); syntax you've seen. It works like
this: $() says, "hey, jQuery things are about to happen!" Putting
document between the parentheses tells us that we're about to work
our magic on the HTML document itself. .ready(); is a function, or
basic action, in jQuery. It says "hey, I'm going to do stuff as
soon as the HTML document is ready!" Whatever goes in .ready()'s
parentheses is the jQuery event that occurs as soon as the HTML
document is ready.So,$(document).ready(something);says: "when the
HTML document is ready, do something!" (We'll show you how to
replace something with an action in the next exercise.)Note that
.ready(); ends with a semicolon. This tells jQuery that you're done
giving it a command.
The Functional ApproachPerfect! Now we need to put something
inside our ready() function.Remember, when we say "function," you
can think "action." Functions are the basic unit of doing work in
jQuery.For this reason, jQuery includes a function keyword. The
syntax looks like this:function(){ jQuery magic;}If we add our
function inside our .ready(), jQuery will run the code in our
function as soon as the HTML document loads. The syntax would then
look like this:$(document).ready(function() { jQuery
magic;});Remember, we end our jQuery statements with a
semicolon.
Get Yourself In...Great! Next, let's include our function
keyword and two new actions together, mouseenter() and
fadeTo().mouseenter() does what you might expect: it produces a
change when your mouse enters a given HTML element. For
example,$(document).ready(function() {
$('div').mouseenter(function() { $('div').hide(); });});would hide
every on the page as soon as you mouse over one. (We'll find out
how to affect just one among many in the next lesson.) For now, we
only have one , so this setup is okay.Instead of hide(), however,
we'll place fadeTo() inside mouseenter(). fadeTo() takes two
arguments, or inputs, between its parentheses, separated by a
comma: the speed at which to fade, and the opacity (or
transparency) to fade to. For example,fadeTo('fast', 0.25);would
quickly fade the target element to 25% of its original opacity,
making it very light-colored.
...and Get Yourself Out!Excellent! Your button looks great nowit
stands out when the user mouses over it.However, you'll notice that
when you take your cursor off the button, it stays dark. What we
really want is for our button to become light again when our mouse
leaves.You might have guessed that jQuery includes a mouseleave()
action. If so, you're right! (If you're curious, you can learn more
about these actions in the jQuery documentation.)
'this' is Important!In the last lesson, we had some code that
looked like this:$(document).ready(function() {
$('div').mouseenter(function() { $('div').hide(); });});The second
line is good: this tells us that when we mouse into a div, we
should take a certain action. However, $('div').hide(); won't just
hide the div you mouse into; it will hide all the divs on the page.
How can we tell jQuery we only want to affect this particular
div?With this, of course!The this keyword refers to the jQuery
object you're currently doing something with. Its complete rules
are a little tricky, but the important thing to understand is if
you use an event handler on an elementthat's the fancy name for
actions like .click() and .mouseenter(), since they handle jQuery
eventsyou can call the actual event that occurs (such as fadeOut())
on $(this), and the event will only affect the element you're
currently doing something with (for example, clicking on or mousing
over).
Toggling Our PanelPerfect! Just one more step: we need to tell
.click() what to do. In this case, when our pull tab is clicked, we
want our sliding panel (with the class .panel) to open or close.The
jQuery event we need to toggle our sliding panel is (you guessed
it): .slideToggle()! We'll pass it one input, which is the speed of
our slide animation.
Creating HTML ElementsDynamically adding elements to our HTML
page is a powerful toolit lets us modify not only the formatting,
but the actual structure of our websites in response to a user's
actions. For example, when you get a Gchat, each message is
actually a new being dynamically added to the page. Cool, right?If
you think about it, we've sort of done this already: all we're
doing is setting a variable equal to a jQuery object. In this case,
however, instead of just having something like:$p = $('p');We'll
want to pass in an entire HTML element in quotes:$p = $("I'm a new
paragraph!");When we put text in quotes like this, we call it a
string (as in a "string of characters"). From now on, when we say
"string," you can think "text" or "phrase." Strings are always in
single or double quotes.
Inserting ElementsWe can insert our newly created elements using
a few jQuery actions..append() inserts the specified element as the
last child of the target element. .prepend() inserts the specified
element as the first child of the target element. If we have a div
of class
.info,$(".info").append("Stuff!");$(".info").prepend("Stuff!");will
add a paragraph containing the text "Stuff!" inside all divs of
class .info. .append() will make the paragraph the last child of
each div; .prepend() will make the paragraph the first child of
each div. (Note: see the Hint if you're using single
quotes.).appendTo() does the same as .append(), but it just
reverses the order of "what to add" and "where to add it." The
code$('Stuff!').appendTo('.info');has the same effect as the
.append() code above. .prependTo() has a similar relationship to
.prepend().
Before and AfterWe can specify where in the DOM we insert an
element with the .before() and .after() functions. The syntax looks
like this:$('target').after('To add');Where 'target' is the element
after which you want to add something and the bit between s is the
HTML element you want to add. You can add s, s, or any other valid
HTML you like.
Moving Elements AroundMoving elements around in the DOM is a
snapall we need to do is use the jQuery functions we just learned
on existing elements instead of creating new ones.var $paragraph =
$("p"); // existing element$("div").after($paragraph); // Move
it!// Same as:$("div").after($("p")); We can select an element
using $("p") and assign it to a variable We can move the position
in the DOM by using the variable in our after() statementNote: This
does not copy the element from one location to another, it moves
the original element effectively saving you from having to delete
the original.
Removing ElementsAdding elements to our HTML documents is great,
but without the ability to remove them, our pages can quickly
become cluttered. Thankfully, we have two jQuery functions,
.empty() and .remove(), that help us delete content from our
pages..empty() deletes an element's content and all its
descendants. For instance, if you .empty() an 'ol', you'll also
remove all its 'li's and their text..remove(), not only deletes an
element's content, but deletes the element itself.
Adding and Removing ClassesWe don't have to limit ourselves to
adding or removing entire elements, thoughwe can fine-tune our
jQuery superpowers to alter classes, CSS, and even the contents of
our HTML elements.Let's start with classes. jQuery includes two
functions, .addClass() and .removeClass(), that can be used to add
or remove a class from an element. This is great if, for example,
you have a highlighted class that you want to apply to an element
when clicked.The syntax looks like
this:$('selector').addClass('className');$('selector').removeClass('className');where
'selector' is the HTML element you want and 'className' is the
class name you want to add or remove.Remember: You aren't selecting
anything, you are modifying your element. This means that you do
not need # or . before your class.
Toggling ClassesWhat if we want to toggle a class back and
forth, though? That is, what if we want jQuery to automatically
check to see whether our #text is .highlighted, so that when we
click on it, it adds the class if it isn't there and removes it if
it is?As you probably guessed, jQuery includes a .toggleClass()
function that does exactly this. If the element it's called on has
the class it receives as an input, .toggleClass() removes that
class; if the target element doesn't have that class,
.toggleClass() adds it.
Changing Your StyleWhat if we want to fine-tune individual CSS
property values, though? Remember style="height:300px;
width:300px;"? jQuery makes it a snap!Because resizing elements is
so common, jQuery has specific .height() and .width() functions
that can be used to change the heights and widths of HTML elements.
For instance: $("div").height("100px");
$("div").width("50px");would give all s on the page a height of 100
pixels and a width of 50 pixels.jQuery also includes a
general-purpose .css() function that takes two inputs: the first is
the CSS element to alter, and the second is the value to set it to.
For example: $("div").css("background-color","#008800");would give
all s on the page a green background color. You can modify any
element's CSS attributes this way.
Modifying ContentFinally, we can update the contents of our HTML
elementsthat is, the bit between the opening and closing tagsusing
the .html() and .val() functions..html() can be used to set the
contents of the first element match it finds. For
instance,$('div').html();will get the HTML contents of the first
div it finds, and$('div').html("I love jQuery!");will set the
contents of the first div it finds to "I love jQuery!".val() is
used to get the value of form elements. For
example,$('input:checkbox:checked').val();would get the value of
the first checked checkbox that jQuery finds.
Click Da Button! Do It Naoughw!You'll notice we've set up an
HTML form for grabbing the user's input. We'll need to store the
user's input in a variable, which will allow us to append that
input to the body of the HTML document later on.You can set a
variable equal to the contents of the input field using .val(),
like so://Get the value from an inputvar input =
$('input[name=checkListItem]').val(); Our selector finds our
specific input using a css selector on our checkListItem inputWe
call val() to get the value of the field.
Remove What's Been ClickedGreat job! Finally, we want to be able
to check items off our list.You might think we could do
this:$('.item').click(function() { $(this).remove();});and that's
not a bad idea. The problem is that it won't workjQuery looks for
all the .items when the DOM is loaded, so by the time your document
is ready, it's already decided there are no .items to .remove(),
and your code won't work.For this, we'll need a new event handler:
.on(). You can think of .on() as a general handler that takes the
event, its selector, and an action as inputs. The syntax looks like
this:$(document).on('event', 'selector', function() { Do
something!});In this case, 'event' will be 'click', 'selector' will
be '.item', and the thing we'll want to do is call .remove() on
this.
Combining .click() and .hover()Well done! Let's add one more
jQuery event to our "destruction of Krypton" simulation. Krypton
didn't just vanish, it exploded! Let's make it turn
red.$('div').hover(function(){ $('div').addClass('green');});
Following the pattern we have been learning, we target Krypton, our
$('div') We then apply our hover event to our target.Finally, we
execute the code inside the function(){} which adds a class of
green to our target.
The .dblclick() EventNow that we've reviewed our jQuery event
handlers, let's learn a new one.We might want to cause a jQuery
effect when a user double clicks on an element, rather than just
single-clicking. We can do this with the .dblclick() event
handler.
HoverWhat if you wanted to create an effect when your mouse is
on top of an object, then have that effect vanish when your mouse
moved away? You might notice this effect in use on many site's
navigation bars!$('div').hover( function(){
$(this).addClass('highlight'); }, function(){
$(this).removeClass('highlight'); }); We first select the element
we want to modify $('div') Secondly notice that our hover effect is
able to take two functions(){} separated by a comma. The comma is
very important! The first function(){} we pass will be run when we
first mouse over our target. Here we apply a class of highlight The
second function(){} will be called when our mouse leaves the
object. This is where we remove the class highlightYour second
function(){} doesn't have to be the opposite of the first
function(){}, but it would be very common!
Let's .focus()!Another event we can make use of is .focus(). We
say an element has focus when we click on it or tab over to it. If
you've ever filled out a form on a web page and seen how each text
box lights up when you tab to it or click on it, you've seen focus
in action!The .focus() event handler only works on elements that
can receive focusthe list of these elements is a bit vague, but
HTML elements like s and s are the usual suspects.Check out the
form we've set up in the Result tab. If you click on the input
field, you'll see it automatically highlights in a delightful baby
blue. Too bad baby blue is for babies! We want our highlighting to
be red.We can do this with two tools: .focus() and our .css()
function from the last section. We want to write a bit of jQuery
code that will change our 'input''s 'outline-color' to 'red' when
it gains focus.The .keydown() EventYou're not limited to mouse
events in jQueryyou can trigger events using the keyboard, as
well!The .keydown() event is triggered whenever a key on the
keyboard is pressed. It only works on whatever page element has
focus, so you'll need to click on the window containing your div
before pressing a key in order for you to see its effects.Let's go
ahead and combine our new event with a new effect: .animate()!
We'll use this to move an object on the screen whenever we press a
key.The .animate() effect takes two inputs: the animation to
perform, and the time in which to perform the animation. Here's an
example:$(document).ready(function() {
$('div').animate({left:'+=10px'},500);});This will take the first
div it finds and move it ten pixels to the right. Remember,
increasing the distance from the left margin moves something to the
right; the += bit is just a shorthand for "take the existing number
and add ten to it." In this case, it add ten pixels to the current
distance from the left margin.
Filling Out the CasesGreat work! Now it's time to animate our
character based on the user's input from the keyboard.Every key
press on a keyboard is translated into a number for the computer to
use. Don't worry about memorizing them, for now we've given you the
basics in script.js// Left arrow key pressedcase 37:
('img').animate({left: "-=10px"}, 'fast'); The left arrow key on
our keyboards translates to number 37 to the computer. When that
key is pressed, we animate our image to the left by subtracting
10px To move up we subtract 10px from the top To move right we add
10px to the left 4, Finally, to move down we add 10px to the topCan
you fill in Up, Down, and Right? What happens if you add pixels
+=10px instead of subtracting?
Introducing: jQuery UIAll right! Time to blaze new jQuery trails
with a new jQuery library: jQuery UI.jQuery UI includes a number of
ultra-fancy animations you can use to make your websites do
incredible things.For instance, remember when we lamented that
jQuery didn't include a .blowUp() effect for our planet Krypton?
Well, that's still true. But jQuery UI has an .effect() effect, and
we are totally going to give it the input 'explode'.Note that we've
included an extra tag in our HTML documents; this is used to
include jQuery UI in our webpages. We don't have to do this with
regular jQuery, since Codecademy automatically includes it for
us.
.bounce()Cool, right? But we can do much more than just blow
things up.Another possible effect is 'bounce'. We give this as an
input to .effect() just like 'explode', but we add an extra input
to tell it how many times to bounce. This code will make our target
'div' bounce twice in 200 milliseconds:$('div').effect('bounce',
{times:2}, 200);
.slide()We can also make Krypton .slide() into view. Not
surprisingly, we do this by calling the .effect() effect and
passing in 'slide' as an input.If you want to see everything jQuery
UI can do, you can check out the documentation here!
Drag RacingjQuery UI includes a .draggable() function that can
make any HTML element draggableyou can click on it and move it
anywhere on the page!We thought you might be tired of blocks, so we
made you a CSS car. We worked super hard on it.PHP
Why Learn PHP?"So what?" You might say. "I can do that with
JavaScript." And that's true! But JavaScript's knowledge can be
limited.JavaScript generally runs in the browser, or client. This
means it only really knows what's going on in your browser, plus
whatever information it gets from the website(s) you're connecting
to.PHP, on the other hand, runs on the same computer as the website
you're visiting, which is known as the server. This means that it
has access to all the information and files on that machine, which
allows it to construct custom HTML pages to send to your browser,
handle cookies, and run tasks or perform calculations with data
from that website.
EchoThe echo function outputs strings. If you type
PHP will output Hello!.Make sure to end your line of PHP code
with a semicolon.
StringsA string is a word or phrase between quotes, like so:
"Hello, world!"You can type a string all at once, like this:
Or use the concatenation operator, which glues several strings
together:
The concatenation operator is just a dot (.). (If you're coming
to PHP from JavaScript, the dot does the same thing for strings
that + does in JavaScript.)
ArithmeticIn addition to outputting strings, PHP can also do
math.
Here we use echo to multiply 5 and 7, and we end our line of
code with a semicolon. PHP will output 35.
VariablesSo far we've been outputting strings and doing math.To
do more complex coding, we need a way to "save" these values. We
can do this using variables. A variable can store a string or a
number, and gives it a specific case-senstive name.Examples:
$myName = "Beyonce"; $myAge = 32;All variable names in PHP start
with a dollar sign ( $ ).
CommentsJust like we sometimes put comments in our CSS (using /*
this syntax */) or in our HTML (using ), we can also put comments
in our PHP code! We do that using two forward slashes (//), like
so:
ComparisonsSo far we've seen: strings (e.g. "dogs go woof!")
numbers (e.g. 4, 10)Now let's learn about comparison operators.List
of comparison operators: > Greater than < Less than = Greater
than or equal to == Equal to!= Not equal to