JavaScript‎ > ‎

Introduction to Javascript


Why JavaScript?

JavaScript is what gives the web its "magic".  The most useful and interesting applications on the internet today are mostly all powered by JavaScript.

Due to the pervasiveness of JavaScript, it has become a very robust language with a huge community of developers.    

JavaScript is what enables the "modern" dynamic page interactions we see today.  

For example:

Flickr Infinite Scroll (scroll down)


JavaScript is platform independent.  Anyone with a modern web browser can use your application.  This also eliminates a lot of the complexities of pushing new versions of your software and managing different binaries for different hardware architectures.  

Businesses need JavaScript developers to  write their apps in accordance with what consumers expect.  This is a very high demand field with a limited pool of qualified applicants.  

Beyond all that, JavaScript is FUN.  What other language do you get to see the result of your work just by refreshing a webpage?  With JavaScript, you get to create engaging user interactions that make the web awesome.


Intro to the JS Console


In Chrome, choose from the triple-line icon:

Tools > Javascript Console

This gives you an area down at the bottom of the screen, called the console. The ">" symbol is called the prompt, and this is where you type things. 

Using the console is a lot like chatting with a friend, or sending text messages. What you are chatting with is the Javascript interpreter, which will interpret or simplify what you say in the best way it knows how. If what you type is already very simple, it will just repeat it back to you.

Simple interpretation

Try typing these lines, pressing enter after each one:

> 4
> "blue"
> 2 + 3

Note that your friend the interpreter mostly just repeats what you say, but may shorten mathematical expressions. It will do some things to pieces of text, too (which we call "strings"). Note that you have to put these pieces of text inside quotes before the interpreter can understand them.

> blue
> "blue"
> "Java" + "Script"

Things we type into the JS Console are just there until we hit refresh. Think of it as a place to play with ideas quickly, not a place to build something that will endure for the ages. We will use it to introduce a few basic programming concepts before trying to use them in a more permanent place... an actual web page. 

Variables and assignment

So far, our friend the interpreter hasn't remembered anything we said from line to line. Not a very good friend! To help it remember, we can tell it we're making a variable.

Variables are names we give to pieces of data for remembering later. Think of a variable name like a sticker you can stick on a piece of data. They're called "variable" because we can attach the same name to different things over time, like a sticker you move from your locker door to your suitcase. 

To attach the sticker, we use an equals sign: "=".

In mathematics this means equality, but in programming languages it means assignment. We're "assigning" a value to the label, attaching the sticker.

Try typing these:

> var color = "blue"
> color
> var color = "yellow"
> color

Don't worry about the "undefined" you get from the "var" lines; the interpreter is just telling you that variable assignment itself doesn't evaluate to anything. It doesn't need to: the point is that the value is remembered for later.

Try playing some more with variables:

> var humanLegs = 2
> var catLegs = 4
> humanLegs
> catLegs + humanLegs
> color + catLegs

Note that variable names are case-sensitive, which means capital letters matter. This will give you an error:

> HumanLegs

You can make one variable out of one or more other variable values:

> var insectLegs = humanLegs + catLegs
> insectLegs

Exercises

What will each of the following produce?  Try to figure it out before you hit enter.

> var hello = "hi"
> hello

> var hello = hi

> var "hello" = "Hi"

> var hello = "Hi " + "Bob"
> hello

> var hello = "Hi " + Bob

> var hello = "Hi "
> var name = "Bob"
> hello + name
> hello
> name

> var hello = "Hi "
> var name = hello + "Bob"
> hello
> name
> hello + name

Calling functions

What's a function? A function is anything that a piece of data (an "object") is able to DO for you, when asked. You've already seen an addition function in action above, every time we said "+", and it turns out that Javascript objects can do lots of other things too.

We'll look at defining our own functions later on. For now, to stay simple, let's just practice calling some functions that Javascript provides for you. Luckily, strings give us a lot to play with.

To call a function, we type:
  • an object name or value (can be a variable)
  • a dot, which means "call a function"
  • a function name
  • parentheses

For example, let's ask the string "blue" to turn itself to upper case for us.

> "blue".toUpperCase()

Sometimes the functions will do different things, based on more values passed to them inside the parentheses. Without going into detail about where these are defined, try calling a couple of these:

> "blue".charAt(0)
> "blue".charAt(1)
> "blue".charAt(2)
> "blue".charAt(3)
> "blue".charAt(4)
> "blue".substring(0, 3)

Why is '0' the 'first' character and '1' the 'second' character?  In programming, all counting begins at 0.

You can call a function on a variable:

> color.toUpperCase()

You can make a new variable from the result of a function call:

> var bigColor = "pink".toUpperCase()

You can call another function on the result of a function call:

"yellow".substring(0,4).toUpperCase()

You can combine these tricks. You can even store the resultant value in the same variable you started with!

> var lemonColor = "yellow"
> lemonColor
> lemonColor = lemonColor.toUpperCase()
> lemonColor

The secret to this mind trip is that the interpreter handles everything on the right side of the "=" before dealing with the left side.

Activities

  1. Given the string var text = "BIGBIGSMALLBIGBIG", make the 'SMALL' portion into a lowercase 'small'.  Store the value back into 'text'.

Lists and associative arrays

Not all variables are as simple as the ones we just saw. We'll need to use more complicated ones in some projects later.

Here's how you define and view a list in Javascript:

> var colors = ["red", "orange", "yellow", "green", "blue", "purple"]
> colors
> var primes = [1, 2, 3, 5, 7, 11]
> primes

You can look at them one at a time by asking for the index of the one you want, which starts at 0 for the first one and counts up.

> colors[2]
> colors[2].toUpperCase()
> primes[5]

You can also edit lists.

> colors
> colors[1] = "magenta"
> colors

You can only ask for an index that exists, or else you'll get an error.

> colors[11]

Why is that useful? It's nice to be able to store a group of things all together, but it really becomes useful when you want everything in a category to do the same thing for you. That's what we're here for, to make things happen!

For loops

Let's do something crazy with a list.

> colors
> for (i in colors) { colors[i] = colors[i].toUpperCase() }
> colors


What happened? We combined a lot of tricks and added a new one, the "for" loop. The "for" loop is about taking the same action on a lot of objects. 

The "i" is a variable traditionally used in for loops; it's short for "index". Every time the loop is called, it gets a number corresponding to the index of the list.  0, then 1, then 2, .... all the way up to the length of the "colors" variable. This lets the loop access different entries in "colors" until it's done everything. And our trick of modifying a variable value lets us update each color name.

Activities

  1. Create a list that stores the numbers 3 through 10.  How would you get the first item in the list?  How would you get the second item in the list?
  2. Create a list named people that stores the names of everyone in your row, in all lowercase.  Write a for loop that capitalizes the first letter of everyone's name.  Make sure to type 'people' into your console at the end, to prove to yourself that it worked!

Associative arrays

Just one concept remains here: the associative array. It's like a list of pairs of objects; or a list of stickers, each of which is stuck to something else. The syntax is different, too.

> var fruitColors = { "apple" : "red", "tangerine": "orange", "banana": "yellow"}

Each sticker/object pair, also called a key/value pair in computer science, is separated from the next by a comma. 

And instead of looking up individual values with an index, we now can use the keys, or stickers.

> fruitColors["apple"]

You will get an error if you ask for something that doesn't exist.

> fruitColors["pear"]

Javascript also allows you to access the values by using a dot, similar to how you call a function. Try this:

> fruitColors.apple

We'll be seeing variables, functions, lists, for loops and associative arrays again later as we work with Javascript in a more permanent context: an HTML page. 

Starting out with a simple page...

Create a new file and paste this into it, then view it in a browser.

<!DOCTYPE html>
<html>
<head>

<style>
  #title {
    text-align: center;
    font-size: 20pt;
  }
</style>

</head>
<body>

<div id='title'>The title of my page</div>

<p>This is the very first paragraph.  There are many paragraphs, but this one is mine.</p>

<p>This is the second paragraph.  Just because it's not <em>numerically</em> first does not make it a lesser paragraph.  We can't <em>all</em> come first.</p>

</body>
</html>

There is no Javascript in this page yet. We'll add some.

Unlike with the console, things we type into the HTML page are part of our page and will always be there.  Conveniently, we'll still be able to use the console to access the Javascript objects in the page -- this will let us work in a quick, experimental way even though we now are adding code in a more pemanent place.

In the HTML, all Javascript will appear between two 'script' tags.  We can either write our code there, or add entire libraries by adding them to the 'script' tags inside the 'head' part of the page.

In addition, Javascript statements in the HTML page must end with a semicolon. This acts to separate one line from another, which we didn't need in the console but we do need in the context of a long file.

Brief jQuery intro


Let's add the jQuery library to our page, because we're going to need it in the upcoming examples:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

<script>
  console.log("Hello!");
</script>

Hit refresh to update the page.

What is this for? 

The purpose of jQuery is to make it much easier to use JavaScript on your website.

jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code.

jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.

Selectors

Selectors are how we "get at" an element or collection of elements on the page.  The collection of elements found is returned from the selector.  This allows us to chain commands onto an existing collection of DOM elements.


> $("p")
> $("#title")
> $("#title").hide()
> $("p").hide()
> $("p").show()
> $("p:first")
> $("p:last")
> $("p:contains('second')")

Once we're able to "get at" an element, we can do things to it.  For example, add a new CSS class inside the <style> tag in your HTML <head>:

  .red {
    background: red;
  }

Hit refresh to reload the page.  Now try this in your JS Console:

  > $("p").addClass("red")
  > $("p").removeClass("red")


Open questions/activities:

  • How would you make just the second paragraph red?
  • How would you make the font blue?


Functions


Here's how you define and call a function:

var f = function() {
  ... do something here...
};

f();

Let's start with a function that just says hello. Add the following between the <script> tags:

var hello = function() {
  console.log("Hello!");
};

Remember to include:
  1. var
  2. The equal sign
  3. The ()s after "function"
  4. Open and close {}s
Refresh the page.
Here's how you call a function on the Javascript Console:

> hello()
> hello()

Let's make a function that makes the paragraphs red.  Add the following between the <script> tags:

 var MakeParagraphsRed = function() {
     $("p").addClass("red");
 };

Refresh the page.
Now call your function on the Javascript Console:

> MakeParagraphsRed()

Note that the function is defined within the HTML page, but it's not run until you call it.

Now we should make an "undo" function:

 var MakeParagraphsRed = function() {
     $("p").addClass("red");
 };

 var UnmakeParagraphsRed = function() {
     $("p").removeClass("red");
 };

Refresh the page and try it out:

> MakeParagraphsRed()
> UnmakeParagraphsRed()


Events

The Javascript Console is great for us, but we don't want users to have to use it.  Let's add two buttons to the HTML part of the page that do the red'ifying for us. Be sure to put them inside the <body> element.

  <input type='button' value='Make Red' id='redify'>
  <input type='button' value='Undo Red' id='deredify'>

Now the buttons exist, but when we push them, nothing happens.  We're going to have to hook them up.

But before we do that, let's look at a simpler example: let's have the page notify us when it's ready to go.  In other words, give us a way to execute code when the DOM is ready.

Add the following bit of code between the <script> tags:
  var Main = function() {
    console.log("Ready to go!");
  }
  
  $(document).ready(Main);

When the page is done loading, our Main function gets called automatically. (Just so you know, this is a feature of the jQuery library, not of the Javascript language. If you remove the script tag that includes the jQuery library, it won't work.)

Hit refresh to try it out.

Okay, so now we can make something more complicated happen when the page loads.  Try replacing the console.log with our MakeParagraphsRed function:

  var Main = function() {
    MakeParagraphsRed();
  }

Hit refresh and you'll see that as soon as the page loads, the paragraphs go red.

Not bad, but not quite what we want.  We want our buttons to control whether or not the paragraphs are red.

  var Main = function() {
    $("#redify").click(MakeParagraphsRed);
    $("#deredify").click(UnmakeParagraphsRed);
  }

We've already seen most of the components of this before. 

When we say $("#redify") remember that that's our way to "get at" the button we made above (we gave it the 'redify' id).  Then we're saying when we click on the button, we want our MakeParagraphsRed function to get called.

Nothing happens until we click on the button.  We call this an "event listener" because it's listening (waiting, watching, in an almost-creepy kind of way...) for a click event, and then when that event happens, it's going to call our function for us.

Try it out.  Hit refresh and try clicking on the two buttons to see if it works!

Open questions/activities:

  • How would you make a button that turned the text blue?
  • What if I wanted to turn the text red on hover, instead of click?

Activity 1: Crazy Dynamic Pages

Looking for more information on selectors?  Check out the JQuery Selector Help Page.

1) Create a function called MakeItalicsPink.  When it gets called, it should turn all of the italics on your page into a pink color.  Call it from the Javascript Console to make sure it works.
Hint: Our italics come from the <em> tag.  So you'll need a selector that finds all the <em> tags.

 > MakeItalicsPink()

2) Create a button that says "PINKIFY" on it.  When you push that button, all of the italics should become pink.

3) Not just buttons can have 'click' events.  You can click on all sorts of stuff!  Don't believe me?  First add this function to the <script> tags:
var ParagraphClick = function() {
  console.log("You clicked!");
};

When the function gets called, it prints stuff out to the Javascript Console.  (You can call it on the Javascript Console to make sure it's working.)

Now make ParagraphClick get called whenever you click on a paragraph.

Hint: You'll need a new line in our Main function that looks similar to the others.  But instead of using the $("#redify") selector, you'll need a selector for paragraphs, which we've seen before.

4) Instead of needing two buttons -- one for addClass and one for removeClass -- jQuery provides a method called toggleClass.  Try replacing addClass("red") with toggleClass("red") and then change your code so you only need one button for turning the red off and on.

5) There are more events than just 'click'!  Try changing some of the 'click' listeners to 'hover' and see what happens.

6) Create an annoying, unclickable button!

a) Do this by making three buttons on your page: #button1, #button2, and #button3 that look the exact same.  Use CSS and HTML to put them anywhere you want.
  
  #button1 {
    position: absolute;
    top: 100px;
    left: 500px;
  }
  
b) When your page loads, hide #button2 and #button3 so it looks like there's only one button.
Hint: Remember that Main gets called when the page loads.

 c) When your victim tries to hover over #button1, immediately .hide() it and .show() #button2.  It will look like the button jumped suddenly!

d) When your victim tries to hover over #button2, immediately .hide() it and .show() #button3.  Do the same thing with #button3.
  
Now watch as they desperately try to click on the buttons.
Think about ways you could make this game more fun and/or evil.


Animation

Let's start off with a new, simple HTML page:

<!DOCTYPE html>
<html>
<head>

<style>
  #kitten {
    position: relative;
    left: 10px;
    top: 10px;
    height: 100;
    width: 100;
  }
</style>


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

<script>
  var Main = function() {
    // Doesn't do anything yet!
  }
  
  $(document).ready(Main);
</script>

</head>
<body>

   <div id='clickme'>
     Click me
   </div><br/>

   <img src='http://images2.fanpop.com/image/photos/10200000/kitten-cute-kittens-10224184-500-445.jpg' id='kitten'>

</body>
</html>

Take a moment to look through the page and see what it does.
  • We have a <div> with the id #clickme that contains the text "Click me"
  • We have an <img> of a kitten with the id #kitten.  And at the top of the page we have some CSS describing the image's size and where we want it on the page.
Right now the div isn't even a button. (Change it to look like a button if you like.) And the button isn't hooked up to anything.  But it would sure be great if clicking on the button or div did something to the kitten.  After all, the internet was built on the back of interacting with kittens.

Let's add a new function and call it in Main:

  var AnimateKitten = function() {
    $('#kitten').animate();
  };

  var Main = function() {
    $('#clickme').click(AnimateKitten);
  }

Now when you click on the button, $('#kitten').animate(); is called.  But we haven't told it what to animate yet.

animate() is expecting a bunch of changes to the CSS of the kitten element.

For example, maybe we want to animate moving the kitten to the right.  Remember that the CSS property left: 100; says "put the kitten on the page with 100 pixels of space on its left hand side.  So if we increase that value, to, say, 200, it would move the kitten to the right.

Here's how we do that:

 var AnimateKitten = function() {
    var changes = { "left": "200" };
    $('#kitten').animate(changes, "slow");
  };

Whew, there's a little bit going on there, so let's break it down.

var changes = { "left": "200" };
is what we want the changes to be to the CSS.  (I picked the name "changes" out of a hat.  It's just a variable name, but it seemed appropriate.  You can name it "Phil" if you want.)  We want the "left" CSS property to be "200" when the animation is done.

changes itself is an associative array, which is something provided by the Javascript language and is basically a lot of pairs. Each pair is a string (like "left") associated with some value, and you can have a long list of them.

$('#kitten').animate(changes, "slow");
says to animate the kitten with the changes above, and to do it "slow".  JQuery also understands "fast", or a number (number of fractions of a second).

Alright, try clicking on the button and see what happens.  Holy crap, right?!

We can do more than just move the left parameter, though.  We can play around with any numeric CSS property.  Try replacing the changes line with this:

var changes = { "left": "200", "height": "1000", "width": "700" };

Okay, before you run it, try to predict what it's going to do.  Try it and see if you were right.

What happens if you click on the "Click me" a second time?

Oooooooo sadface.  It only works once.  That's because the 'left' value is already 200, so it has nowhere to move to.  And the 'height' value is already 1000.  etc.  If we want the button to work multiple times, we need it to increase every time.

Here's how you change the value every time:

var changes = { "left": "+=50"};

Run that and see what happens now when you click the "Click me" multiple times.  Yay!

Activity 2: The Moveable Box

Create a square box and four buttons (labeled "up", "down", "left" and "right") that move the box around.

  <div id='box'></div>
  
  #box {
    background: silver;
    height: 50px;
    width: 50px;
    position: relative;
  }

Hint: "left": "-=10" is the opposite of "left": "+=10"!

Once you've got that working, why not add some interactivity to the box.  Make something happen when you hover over it or click it.  There are other animations you can play around with listed on the JQuery Animation Help Page.

Dynamic Data

Let's start with a new, simple HTML page again:

<!DOCTYPE html>
<html>
<head>

<style>
</style>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

<script>
  var Main = function() {
    // Doesn't do anything yet!
  }
  
  $(document).ready(Main);
</script>

</head>
<body>

       I am so lonely!

</body>
</html>


Totally empty.  The world's most boringest page.  (Though you might want to cut and paste this page when you go to create new ones for yourself.)

Let's add some data to it!

<script>
  var animal = {
    "name": "Joe",
    "type": "camel",
    "legs": 4,
    "features": "hump"
  };

  var Main = function() {
    // Doesn't do anything yet!
  }
  
  $(document).ready(Main);
</script>


We just created a new variable named animal .  He has several properties, but the easiest way to poke around at him is to open the Javascript Console.

 > animal
 > animal.name
 > animal.type

What if we wanted multiple animals?  In Javascript, that would look something like this:

<script>
  var zoo = [
  {
    "name": "Joe",
    "type": "camel",
    "legs": 4,
    "features": "hump"
  },
  {
    "name": "smokey",
    "type": "bear",
    "legs": 4,
    "features": "scared of forest fires"
   }
  ];

  var Main = function() {
    // Doesn't do anything yet!
  }
  
  $(document).ready(Main);
</script>

The easiest way to see what's going on, again, is to look at our zoo variable in the Javascript Console.
 
 > zoo
 > zoo[0]
 > zoo[1]
 > zoo[1].name

So we have these two animals hanging around in a variable called zoo.  What can we do with them?

Well, first of all, we can use Javascript to tell our users what they are.

First, add a little bit of HTML where our list of animals is going to go:

<body>

       The animals at our zoo are: <ul id="animals"></ul>

</body>

If you refresh the page now, you'll see an empty, boring list.

We're going to need a function to add items to that list.  And here's what that function will look like:

  var zoo = [
  {
    "name": "Joe",
    "type": "camel",
    "legs": 4,
    "features": "hump"
  },
  {
    "name": "smokey",
    "type": "bear",
    "legs": 4,
    "features": "scared of forest fires"
   }
  ];

  var AddAnimal = function(animal) {
    $("#animals").append("<li>" + animal.name + "</li>");
  };

How does it work?  Well, let's try it out first.  Open up ye ol' Javascript Console:

  > zoo[0]
  > AddAnimal(zoo[0])
  > AddAnimal(zoo[1])
  > AddAnimal(zoo[1])

So when we call 'AddAnimal', we pass in one of our two zoo animals (either zoo[0] or zoo[1]).  The function then looks for an element with the id "#animals" (remember, that's the id we created just a moment ago for the <ul> list).

Then it appends a new html element with the <li> tag and the animal's name in it.

Now let's wire it up to automatically fill up the list when the page gets loaded!

var AddAnimal = function(animal) {
  $("#animals").append("<li>" + animal.name + "</li>");
};

var AddAllAnimals = function(animals) {
  for (i in animals) {
    AddAnimal(animals[i]);
  }
};


var Main = function() {
  AddAllAnimals(zoo);
}

Starting at the bottom, we see that when the page loads up, an AddAllAnimals function is called with the zoo argument (our collection of both animals).

So every time the loop is called, it gets a number corresponding to the index of the list.  0, then 1, then 2, .... 

So the first time around in our loop, we add the 0th zoo animal.  The second time around, we add the 1th zoo animal.  etc.

Javascript is automatically using this zoo data to populate the page.

Okay, but why should you care?  Why couldn't we have just typed the list into the HTML in the first place?  Cuz it's about to get craaaaaaaaaaaaaazy!!


JSON: Calling APIs

Before we get started with APIs, go visit this URL and try to figure out what it does:


Hint 1: It has something to do with kittens.
Hint 2: It's similar to our zoo variable from earlier.

This is a list of search results from flickr, the photo site, when you search for "kittens".  (Why kittens?  Take a close look at the URL.)

You'll see a messy list of things that look kinda like this:

{"id":"9143325327",
"owner":"8519341@N08",
"secret":"c557235572",
"server":"2858",
"farm":3,
"title":"Geez mom, stop taking my picture! #cat #cats #kitty #kitties #kitten #kittens #love #animals #animal #pet #pets #black #instacat #instakitty #instagram #like #likes #follow #vintage #life"},
This is a list of objects, just like how our zoo variable was a list of animals.  And each object has a title ("Kittens"), a link, a date when the photo was taken, an author, etc.
No human being typed this list up.  It's automatically generated.  And every time someone submits a photo to flickr, it updates.
Because it's a little hard to see what's going on in that URL with all the clutter, here's a simplified version.  Try adding it to the top of your <script> tags:
var photos = [
{"id":"9136491524",
                 "owner":"58624514@N07",
                 
"secret":"0aeb34a48d",
                 
"server":"7407",
                 
"farm":8,
                 
"title":"sixteen: archie"},
{"id":"9143325327",
                 
"owner":"8519341@N08",
                 
"secret":"c557235572",
                 
"server":"2858",
                 
"farm":3,
                 
"title":"Geez mom, stop taking my picture! #cat #cats #kitty #kitties #kitten #kittens #love #animals #animal #pet #pets #black #instacat #instakitty #instagram #like #likes #follow #vintage #life"}
];

var zoo = [

This is still an awful lot to try to parse.  Fortunately, it makes a lot more sense when you examine the data with the Javascript Console:
> photos
> photos[0]
> photos[0].owner
> photos[0].title
> photos[1].owner
> photos[1].title

Instead of having our app print the zoo animals from before, let's change it to show the kitten images.

(You can delete all the animal and zoo variables now, if you like.)

var GetFlickrUrl = function(photo) {
  return 'https://farm' + photo.farm +
         '.staticflickr.com/' + photo.server +
         '/' + photo.id + '_' + photo.secret + '.jpg';
}

var AddPhoto = function(photo) {
  $("#photos").append("<li>" + GetFlickrUrl(photo) + "</li>");
};

var AddAllPhotos = function(photos) {
  for (i in photos) {
    AddPhoto(photos[i]);
  }
};


var Main = function() {
  AddAllPhotos(photos);
}

<body>

      Here are some photos: <ul id="photos"></ul>

</body>

Save and refresh.  We're close!  But we actually want the images, not the URL of the images.

var AddPhoto = function(photo) {
  $("#photos").append("<li><img src=\"" + GetFlickrUrl(photo) + "\"></li>");
};

Note the backslashes used to "escape" the " characters so that we can use the string delimiter, ", as part of a string.

Now let's get rid of our annoying hard-coded simplistic example, and use the real data live from flickr!

var DisplayPhotos = function(flickrPhotos) {
   AddAllPhotos(flickrPhotos.photos.photo);
};

var Main = function() {
var flickr = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=764a4955d5ea19e5e7ca0b4a8f9603a7&format=json&jsoncallback=?";
var params = { "tags": "kittens" };
$.getJSON(flickr, params, DisplayPhotos);
}

We're doing three things here:
  1. We're creating a variable called flickr that stores the URL from earlier (except we took out the &tags=kittens part).
  2. We're creating a variable called params that stores the URL parameters, saying that "tags" should be equal to "kittens".
  3. We call $.getJSON which is a jQuery method that takes three arguments: a URL, some parameters, and the name of the function to call with the result.  In our case: our DisplayPhotos function.
Try it out!

Pretty nifty, huh?  And if you look at how much code is left in our file, it's not a lot, considering the fact that we now have an app that displays the latest flickr kitten photos.


Activity 3: Your Awesome Photo Search Engine


1) Instead of loading all the photos when the page loads, create a button called 'Load' and make all the photos load when you hit the button.

2) Kittens are cute, but what about dog people?!  Why not let the user of your webpage decide what they want to search for.

Create an input field, in the HTML body, where users can enter anything they want:
  <input id='searchbox'>

Then in your Javascript code, replace:
  tags: "kittens"
with:

  tags: $("#searchbox").val()
  
This will set the value to be anything that's in your search box.
Give it a try!

3) A lot of extra information comes back with the response from flickr.  Here's some ideas of features to add:
  •   Display the name of the photo along with photo itself
  •   When you hover over a picture, show the author's information
  •   When you click on a picture, go to the flickr page
  •   Create a 'clear' button that deletes all the results by calling: $("#animals").empty()
  •   When you do a search, empty the list (maybe using the clear info above) before you fill it, so that the old results disappear
  •   Add some CSS and maybe some animations or other events to make the whole page prettier
The possibilities are endless.  Make the app your own!

Comments