Giter Site home page Giter Site logo

dinolove's Introduction

nodestart

A simple example Node.js project

dinolove's People

Contributors

alicedilemma avatar courtneeey avatar emilytoshiko avatar jennychow170 avatar jparulian avatar ltkiwi avatar mgatland avatar mieket avatar

Stargazers

 avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

dinolove's Issues

Save and display the author of each idea

Only take this ticket if #4 is done

Act 1

  • in post.html, add a new <input> field to the form where the user can write their name. So there will be a field for your idea and a field for your name.
  • Make sure your new <input> field has a unique class name, e.g. class="nameInput"
  • Check: open localhost:3000/post.html and check your new input field appears on the form.

Act 2

Now we need to send the author text to the server when they click 'submit'.

  • Look at the instructions for issue #2, Act 3. Note how we get a value out of an input, and how we add it to the data object so it will be sent to the server.
  • Now make it so when the user clicks 'submit', the author text is added to the data object and sent to the server. You will need to add one line to the javascript in post.html. This will be very similar to the line that starts with data.idea =โ€ฆ but will need to set data.author instead.

Act 3

Now it's (hopefully) being sent to the server, we need to teach the server to look out for this new information.

  • We're now working in server.js
  • find for the code that is run when a user POSTS a new idea to the server.
  • there is a line that writes the idea text to the console using console.log(request.body.idea);. Add another line that logs request.body.author as well. ('author' needs to match whatever you saved it as in the data object back in feed.html)
  • Restart the server, submit a new idea and check that your author name now shows up in terminal/command prompt.
  • If the author name is coming through, we can now save it. You do this by setting a new new name-value pair on the idea. Your code might look like this:
idea.author = request.body.author;

Act 4

  • Save some new ideas then check how they look in raw form at http://localhost:3000/ideas โ€“ each idea should have a text and an author. (Do any of the ideas not have an author? Maybe just the first one? Do you know why that could be?)
  • modify feed.html so that each post displays the idea's author (idea.author) as well as the idea's text.

notes

This task does not include updating the CSS look + feel of the post.html page. Just make it work, don't focus on making it pretty in this ticket.

Make submit not go to a new page

Currently, when you click 'submit' on the post.html page, you are taken to a new page that says "Thanks for your idea"

This is confusing and not very attractive.

After this change, when you click submit,

  1. you stay on the same page
  2. a little box pops up that says "Thanks! Your idea was saved!"

All these changes are in post.html

Act 1

  • You will need to include jQuery in the page if it is not already included. You do this by adding one line of HTML code to the HEAD of the page. Google "how to add jquery to a page", or look in the head of the feed.html for the line you need to copy.)

jQuery is a library (a whole lot of javascript code that someone else wrote so we don't have to).

Use jQuery to make something happen when you submit the form. To do this:

  • in the html, add a class to the <form> so we can find it using javascript
  • add a pair of <script> tags so we can add some javascript between them. Add these near the end of the file, just above </body> and </html>
  • in your script, use jquery to find the form, using its class name. (Do you remember this from the previous activities?). In the star activity we made things happen on click. Here we want to make things happen on "submit", so you'll end up with a line of code like this in your script:
$(".formclassname").on("submit", myCoolFunction);
  • make a function that will be called when the form is submitted.
var myCoolFunction = function (e) {
    e.preventDefault();
}

The line 'e.preventDefault()' disables the browser's built in action (which is to go to a new page).

  • TEST: clicking 'submit' should now do nothing! yay :/

Act 2

history lesson (you can skip this):
Currently, this page works using an old school technique from before JavaScript was a thing. In the HTML is a form. A form is just like a paper form - you fill it in. When you press 'Submit', your browser takes all the things you wrote, puts them together into a message, and POSTs it to the address specified at the top of the form. Then your browser waits for the response from the server. When it arrives, it displays the response ("Thanks for your idea").

In your new function, we now need to make it do a POST that sends the right info to the server.

You could look up "how to POST using jQuery" on google and find some examples, but to save you time I've pulled a good example out here:

      var data = {};
      $.post( "url" , data );
  • add that code to your function. Change the first argument from "url" to "/ideas" - this is where we are posting to. (It has to match the url the server is listening at in our server code in index.js)
  • TEST: clicking submit should now add a new idea to the ideas feed - but it will be null.

Act 3

How do we get the words the user typed in, and send them to the server?

We will use jQuery to get the part of the HTML page the user is typing into.
Just like the form, we should give this part of the HTML a class so our javascript can select it.

  • Add a class to the <input> where your idea goes. i.e. class="ideaInput"

Now we can select it with jQuery, and get the value out of it using the .val function.

data.idea = $(".ideaInput").val();

You'll need to add the line above just after the line var data = {}. That means, after we create an empty object named 'data', but before we send the object to the server, we add some information to it.

  • Test: you should now be able to correctly submit ideas again.

Act 4: show feedback

  • Add an empty div to the page with a special class like 'note' i.e. <div class="note"></div>
  • In your function, tell jquery to select that div and change the text inside it to say "Thanks! Your idea was submitted!" using some code like this: $(".note").text("Thanks! Your idea was submitted");

Now whenever your function runs, it adds that text into the note.

add a favicon

the favicon is the little icon that displays in your browser tabs or bookmarks.

Making favicons work right on all devices takes a bit of work and I'd normally use a tool that helps you get it right.

However for Girl Code let's do it by hand and just handle the most common cases.

We'll need some .png image files from our Art Team or whoever wants to make some images.

  • one small one that's 16x16 pixels
  • one that's 32x32 pixels
  • if you want, another one that's larger (any size but must be square)

Once we've got the .png image files, put them in the public folder so we can link to them, then we need to add links like this to the <head> of each html page:

<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16.png">

Try it out, you should see the favicons appear in your browser.

Random compliment button

As a dinolove app user, I am too busy to make up my own compliments. I want the app to make up compliments for me.

In this ticket, we will add a new button to post.html. When you click on the button, the computer types in a dino compliment automatically for you.

Act 1

  • In post.html, add a link (our button is going to be a link). Give it href="#" (which means it won't go actually take you to a new page when you click on it). Give it class="generateButton" so our JavaScript can find it.
  • Check that your link appeared on the page. You'll need to put some text inside it or you won't be able to see it!

Now we need to add some JavaScript code to the same page (so look in the <script> tags.)

  • Add this function, which will replace the idea with a new generated idea when it is run:
  var generateCompliment = function () {
    var randomCompliment = "you are nice, dino!";
    $(".ideaInput").val(randomCompliment);
  }

Then make the generate button call that function when clicked, with this line:

$(".generateButton").on('click', generateCompliment);
  • Check: Clicking the generate link should automatically insert a nice compliment into the form. But... it's always the same compliment.

Act 2

(Maybe commit your changes now, before the next step. That way, you can easily go back to this point if things get confusing!)

Instead of always inserting the same compliment, make a random compliment. Do you remember our TV Show Idea Generator activity? Take a look at your code from that.

How would we generate a random compliment? Here's one idea:

Hi name, you have a nice thing.

name could be picked from a random list of nicknames (e.g. "dino friend", "spikey")
nice could be a word like "nice", "impressive", "wonderful"
thing could be a noun like "nose", "disposition", "smile", "tail", "roar"

Give each post a unique ID on the server

Lets give each post a unique ID number. This will be helpful when we want to do something to a particular post (i.e.if we wanted to increase its Like Counter).

All these changes are In index.js

Step 1

  • Create a variable to keep track of our id counter. Put it somewhere near the line var coolIdeas = [], because that's where we set everything up.

Add something like this

var counter = 1000;

step 2

When we create an idea, just before we push it onto the ideas list, we should give it an ID, using the counter. Then we need to increase the counter (so it will give a different number to the next idea.)

You'll need code like this in the right place:

idea.id = counter;
counter = counter + 1;

Once it's working, you should be able to add a few ideas then look at http://localhost:3000/ideas and every idea should have a different ID number.

  • check that every post gets a unique ID number

Step 3

Now our posts have unique ids, we can give our server a function to get a particular post when we ask for it.

In index.js, let's make a new special GET request that the server listens to.

app.get('/idea', function (req, res) {
   var searchId = req.query.id;
   console.log("Searching for post " + searchId);
});

Try it out by restarting the server then going to an address like this: http://localhost:3000/idea?id=1000

If you look at the Terminal\Command Prompt, you should see "Searching for post 1000" (or whatever number you put in the request).

But it doesn't actually search for the post yet.

How do we find the right post?

If you've been doing some homework you might have an idea of how to make it work - basically, the server will need to use a loop to look through every post. For each post, it will check if that post has the right id. If if it does, it send it back using res.send(whatever)

If you don't know or you're stuck, this should help:

coolIdeas.forEach(function (idea) {
    if (idea.id == searchId) {
        res.send(idea);
    }
});

Test that it's working by going to http://localhost:3000/idea?id=1000 again. This time it should show the first post.

Pics feature - user can include a picture with their post

***This can only be done when #4 has been completed

The post form in post.html should let you include a link (URL) to an image file

Act 1

  • on post.html, add a new text input field inside the form. This is where the user can paste in the url of an image.
  • in post.html, update the javascript so it sends the new form field to the server. (Look at the existing code for reference. You only need to add one line.)
  • use the Chrome Developer Tools to check that it's posting the new value when you post.

How to check what is being sent to the server:

with post.html open in Google Chrome, open the Developer Tools
Click on the Network tab
Now on the form, click 'submit'
You should see a new item 'post, appear in the Developer Tools. This line is the POST request. Click on it to see what happened
Choose the Headers section, scroll to the bottom to see the form data, and make sure all the form fields are visible - that means they were sent to the server.

Act 2

  • on the server (index.js), look for the code that runs when an idea is POSTed (it starts with app.post and calls a function) You need to add a line to that function so that the image url is saved into the idea object.
  • check that the image url is being saved by looking at the raw ideas at http://localhost:3000/ideas - do you see the image urls appearing?
    (Remember that because you're changing index.js you'll need to restart your server)

Act 3

  • Now we have these images, we need to display them in the feed. In feed.html, you will need to modify the code that creates each post so that it includes the image URL. This will include some careful use of quotation marks, pluses, and HTML tags. Remember that the final output you want (to create a valid image) is like this: <img src="http://example.com/image.jpg">

PROTIP: In Javascript, strings can be surrounded by a pair of "double quotes" or by 'single quotes'. Whatever type of quotation marks you use, you can use the other kind inside the string. For example, var myString = "I said 'hello'" or var myString = 'I said "hello"' (look really closely!)

BONUS PROTIP: If the line is getting so long it goes off the screen and it's hard to work on, you can split it up. Here's an example how:

//Before:
var ideaElement = $('<div><a href="whatever">click here</a> and then some words, ' + myName + '</div>');

//After:
var reallyLongString = '<div>';
reallyLongString += '<a href="whatever">click here</a>';
reallyLongString += ' and then some words, ' + myName;
reallyLongString += '</div>';
var ideaElement = $(reallyLongString);
//both of these have the same result.
  • TEST: you can now post glorious images to the ideas feed
  • Extra for experts: if the user leaves the image link blank, replace it with the url of a nice default image before saving it

Make post page look nicer

Our post.html page looks really bad. Let's improve it! It's not important to get the design looking perfect yet, because we will probably end up changing a lot as we expand the site, but improving it a little will help us figure out where to go next.

Use html and css to layout the post.html page in a more appealing way
It should have fields for:

  • the idea (text)
  • the author's name (text)
  • a submit button

Note 1: To override the submit button's default style, you need to give it a CSS border rule i.e. border: none; or border: 1px solid black;
Note 2: You can write CSS rules for different types of <input> tags using square brackets, like this:

input[type=text] {
    color: red;
}

input[type=submit] {
   color: blue;
   border: none;
}

here are some examples to give you ideas:

screen shot 2015-11-19 at 3 59 42 pm
screen shot 2015-11-19 at 3 58 44 pm
screen shot 2015-11-19 at 4 00 59 pm

Change feed layout to include author, name, picture and time with idea

Our feed is eventually going to have a list of posts, each post will have

  • the idea
  • the idea's author name
  • the time the idea was saved
  • a picture for the idea

For now we can use placeholders, for example just write "anonymous" where the author will go.

Working on feed.html

  • add placeholder author to each post
  • add placeholder timestamp to each post (eg "today")
  • add placeholder image to each post and use CSS to make it an appropriate size

an example

screen shot 2016-03-09 at 7 37 45 pm

Some extra notes: In feed.html, you will need to modify the code that creates each post so that it includes the image URL. This will include some careful use of quotation marks, pluses, and HTML tags. Remember that the final output you want (to create a valid image) is like this: <img src="http://example.com/image.jpg">

PROTIP: In Javascript, strings can be surrounded by a pair of "double quotes" or by 'single quotes'. Whatever type of quotation marks you use, you can use the other kind inside the string. For example, var myString = "I said 'hello'" or var myString = 'I said "hello"' (look really closely!)

BONUS PROTIP: If the line is getting so long it goes off the screen and it's hard to work on, you can split it up. Here's an example how:

//Before:
var ideaElement = $('<div><a href="whatever">click here</a> and then some words, ' + myName + '</div>');

//After:
var reallyLongString = '<div>';
reallyLongString += '<a href="whatever">click here</a>';
reallyLongString += ' and then some words, ' + myName;
reallyLongString += '</div>';
var ideaElement = $(reallyLongString);
//both of these have the same result.

Center "post" page

Because at the moment all the textboxes and images are left aligned and I feel like it would look better if its centered.

Default picture if user doesn't include a picture

If the user leaves the image link blank, include a cute default picture.

Make the change in index.js at the point when it recieves a POST request. Just before it saves the post, check if the image url is an empty string (i.e. if it === "") and if it is, set it to be a link to a nice default image instead.

new stuff at the top instead of bottom

Currently new posts are displayed at the bottom of the page. Let's put them at the top instead (like twitter, tumblr etc does it.)

In feed.html, we need to reverse the order of the posts, after we GET them from the server but before we display them.

Once you figure out where in the code to do this, actually doing it is simple. If the list object was called data, we'd use this line:

data.reverse();
  • Do you kinda feel like the nav bar should be at the top of the page now? You should move it.

(how did I know to do this? I googled 'javascript array reverse' and found this page: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse )

link buttons jump to top of page

In post.html when you click on the 'LOVE' button (to generate a phrase) or on any quick pic button, the page scrolls up to the top.

This is because you're clicking on a link that links to "#" which is the top of the page.

We need to prevent the built-in behaviour.

Whenever we call a function using something.on("click", myFunction) the myFunction gets passed a special event object. In the funtion that we call, we need to give that object a name by putting it in the function definiton like this

var myFunction = function (e) {

(so we added the e)

Now inside the function, we can prevent the default action with this command:

e.preventDefault();

This tells the browser to disable the built-in behaviour that comes from clicking the link.

  • LOVE button no longer scrolls up
  • each dino pic no longer scroll up

Publish the app on Heroku

Heroku is a host that will run our app online so anyone can access it

You may have to make some changes to get it working

  • 1 [ ] we need to tell Heroku how to start our program. You start it by running node index.js, so we need to add that instruction into package.json somehow. Google "package.json start index.js" and you should find an example
  • 2 [ ] in index.js, the port it listens on probably needs to change from 3000 to (process.env.PORT || 3000) - which means "get the port number from the configuration, or if it hasn't been configured, just used 3000.
  • now try deploying to Heroku again and see if it starts up without errors
  • You can link Heroku to Github so it automatically deploys. Do this so Girl Code automatically deploys from now on. (Look up 'automatic github deploy' the Heroku documentation. You do this step by logging into the Heroku website and going to settings or something.)

change the home page to be the feed page

Currently if you visit http://dinolove.herokuapp.com/ you'll be taken to the home page (index.html) but there isn't actually anything useful here!

We should make our feed page the home page!

  • Delete index.html and rename feed.html to index.html
  • Check that the navbar links still work (they will probably need updating...)

Don't make me delete the example text in the form fields

As a user, when I want to post a cool Dino Love idea, I have to backspace away the example idea to put in my idea. AND I have to backspace away "put in your name" to put in my name. AND then I have to delete "Add dinosaur picture" to put in my picture URL!

When I start typing in the text box, that example text should just disappear automatically. Ghost text! ๐Ÿ‘ป

Fortunately this feature is built into modern browsers so we don't need to code it ourselves.

  • In post.html, in each of the input elements that the user can type text into, instead of setting the value (which is meant to be for what the user enters), set the placeholder instead.
  • test that the page looks and works correctly.

Auto update the feed

As a user, if I'm looking at the feed and someone else posts, I want to see their post appear at the top of my feed. I don't want to have to keep refreshing the page #lazy

Act 1

All these changes are in feed.html

Currently, the feed is created when this line runs

$.get("/ideas", createFeed);

We are going to be running that code over and over again, so let's put it inside a function so we can reuse it. Once you have put the code inside a function, you'll need to call it so that it runs when the page loads.

  • Put that code in a function.
  • Add a line that calls the function. (You do this by writing the function name and putting a pair of round brackets afterwards, like superFunction())
  • check: the page should now work just like it did before

Act 2

We want to call our function every second. Do you remember the Stopwatch activity, where we called a function over and over again to make the timer count down? We need to do the same thing here. (Google 'setInterval' if you need some clues.)

  • use setInterval to call the function every second.
  • Does it work? What is wrong? Any idea how to fix it?

protip: if you wanted to delete all the children of an HTML element, you could do it by selecting the element then calling .empty(), like this::

$(".idea-box").empty();

compliment generator knows when to use 'a' and when to use 'an'

Than random compliment generator isn't very good at grammar.

For example: Hi! You buckbeak have a adorable hair

Let's change it so it uses 'a' or 'an' depending on the adjective chosen.

Because we don't have much time we're going to use a sneaky quick fix and add the 'a' or 'an' to the adjective string (nice in post.html)

so instead of:
nice.push("particularly appealing");
nice.push("adorable");

we'll have
nice.push("a particularly appealing");
nice.push("an adorable");

  • change all the adjective strings that get pushed to nice
  • then change the string that puts the compliment togther
  • check your changes worked!

add more quick pics

We have heaps of pics in our public folder! Let's add a few more to be default quick pic buttons.

Don't lose posts when server restarts

To keep the posts saved even after the server restarts, we need to save them somewhere else.

We're going to use mongoDB, a database, to store our posts. Girl Code has already signed up with a company that provides free Mongo databases, so we won't need to set up the database ourselves - we just need to make our app connect to the database.

add mongodb dependency

Open package.json, find the list of depenencies and add this one:

 "mongodb": "^2.1.0"

(It needs a comma afterwards unless it's the last dependency in the list)

You will need to run npm install at the command line to tell node to download this new package for you.

add some database code

Near the start of index.js, add this code which declares an empty variable:

var database = null;

At the end of index.js, add this code. It connects to the database, and updates the variable so we can use the database elsewhere in our code.

It then grabs a collection out of the database, and adds every item in that collection to our users list.

var mongodb = require('mongodb');
var uri = 'mongodb://user:[email protected]:15919/girlcode16t1';
mongodb.MongoClient.connect(uri, function(err, newdb) {
  if(err) throw err;
  console.log("yay we connected to the database");
  database = newdb;
  var dbPosts = database.collection('posts');
  dbPosts.find(function (err, cursor) {
    cursor.each(function (err, item) {
      if (item != null) {
        coolIdeas.push(item);
      }
    });
  });
});

Test that out, you should see a message log to the console.

Now we need to tell our server, every time it saves a post to its own local list, it should also send a copy to the permanent copy of the list in the mongo database.

Find the saveNewIdea function in index.js that is run when someone posts a new idea.

Add these lines to the end of the function code, so save the idea object to the database as well

var dbPosts = database.collection('posts');
dbPosts.insert(idea);

Now all our posts are recorded in the database. When you restart the server, it will get all the old posts from the database, instead of starting empty.

Give eveRy post a unique ID number

This a behind-the-scenes change that will let us do cool stuff later!

Background:

Imagine you want to 'like' a post, or reply to it. We need a way of saying which post you are talking about! We could use their position ("I want to reply to the 2nd post"), but that could get confusing if we ever reorder the posts, or delete one. It's simpler if we give every post its own ID number (just like a student ID number)

Part 1

In index.js, when we create a new post, give it a random ID number

idea.id = Math.round(Math.random() * 10000);

This isn't a very good way of giving out ID numbers (do you know why?) but it's good enough for now.

How to check your change is working

  • Remember to kill and restart the server first.
  • post a new post
  • Go to http://localhost:3000/ideas and see if your new post has an ID number.

Did you notice the example post has no ID? (this is the post that comes up before you add any other posts). You'll need to add another line where we create the example post (in index.js) that gives it an ID. Instead of a random ID, let's always give it idea.id = 1001;

Optional side adventure

In Chrome, open the Developer Tools and choose 'Console'

Try typing these commands into the console (hit Enter after each one) and see if you can work out what each command does:

Math.random()
Math.random() * 1000
Math.round(Math.random() * 1000)

OK back to work (Part 2)

Let's include the ID in the feed.

Open feed.html

Find the code where we create each post. You will see that we insert various things into the html, like idea.text, idea.author, maybe idea.timeโ€ฆ You need to add idea.id.

Put idea.id inside a new <div> tag and give it class="postId".

If the line of code you're working on is getting too long and annoying, you can add a line break anywhere that's not inside quotes. For example

var ideaElement = $('<h2>' + idea.text + ' , ' + idea.author +  " " + "<div class='time'>" + $.format.prettyDate(idea.time) + "</div>"

works just like

var ideaElement = $('<h2>' + idea.text + ' , ' 
+ idea.author +  " " + "<div class='time'>" 
+ $.format.prettyDate(idea.time) + "</div>"
  • Check: the post ids are now displayed in the feed.

Don't worry about making it look good, because we are going to use CSS To make it invisible!

In the style.css file, add a rule to make the ids invisible:

.postId {
    display: none;
}

The ID will still be there if you view the source (using the Developer Tools), and our code will use later on. But it's invisible to users.

Part 3

Now our posts have unique ids, we can give our server a function to get a particular post when we ask for it.

In index.js, let's make a new special GET request that the server listens to.

app.get('/idea', function (req, res) {
   var searchId = req.query.id;
   console.log("Searching for post " + searchId);
});

Try it out by restarting the server then going to an address like this: http://localhost:3000/idea?id=1001 that's idea without the s, not ideas

If you look at the Terminal\Command Prompt, you should see "Searching for post 1001"

But it doesn't actually search for the post yet.

How do we find the right post?

The server will need to use a loop to look through every post. For each post, it will check if that post has the right id. If if it does, it send it back using res.send(whatever)

This example should help:

   var results = posts.filter(function (post) { return post.id == searchId; });
   if (results.length > 0) {
     res.send(results[0]);
   } else {
   res.send(null);
   }

Test that it's working by going to http://localhost:3000/idea?id=1001 again. Instead of 1000 put in the id of an actual post. It should show details of that post.

Notifications! for real this time

hi ok we know how do do notifications now

On the Server Side

subscribers

We need to keep a list of ids for people who are subscribed to notifications.

var subscribers = [];

We need to create a new POST address where clients can post their ID to us. When someone posts an id to dinolove.com/subscribe, we should add the ID number they give us to the list.

Sending messages

To send a message to our subscribers, we need to do a POST from our server to Google.

We could write the code ourselves, but let's try this library first: https://www.npmjs.com/package/gcm

It provides an easy way to send messages. We'll need to loop over each subscriber and send one message to each of them.

On the client side

The code we did in the tutorial. The client needs to create a worker, then the worker says it wants to subscribe to notifications.

We'll have to add one extra step: the client needs to post a message to our server, telling our server its id number.

I don't know if our web worker is allowed to do the post itself - it might be, but if it isn't, it will have to send a message back to the page (saying what the ID is) and then the page will have to do the post.

Update the look of the navbar

Let's make the navbar look a bit more navbar-y.

  • look at the headers of a few of your fav social media sites for inspiration
  • put the links in a header
  • add some css

Dino quick pics

As a user, I'm sometimes too busy to find my own dinosaur picture on the internet. I would like a few buttons I can click that automatically insert cool pictures. #lazy

Act 1

All these changes are in post.html.

We're going to add a button that has an image of a dinosaur. When the user clicks the button, the correct url for that image is inserted into the urlInput field of the form.

I say 'button' but this will actually be a link which contains an img. (When something is inside a link, it becomes clickable like the link.)

  • Add a link with an image inside to the page. Find the URL of a nice dinosaur picture and put it in as the image url.

Example:

<a href="#" class="quickpic1"><img src="http://example.com/dinosaur.jpg"></a>

Note that I made that link go nowhere (href="#") and gave it a class "quickpic1" so we can find it in JavaScript. I didn't find a real dino pic, you have to do that yourself.

Now to make it work. First we need a function that changes the url of the urlInput field. You can add this to the JavaScript and put in your url:

var setPic1 = function() {
    $(".urlInput").val("http://example.com/dinopic.jpg");
}

Secondly, you need to make it so clicking the link calls that function. We did a lot of this back at the start of the course (in the Five Star, Cat City, StopWatch activities). Do you remember?

  • make clicking the button run the function
  • check it works

Act 2

  • add a few more buttons with different dino pics
  • add some CSS that makes the buttons look nice. If you want to style all the buttons with the same css, you can add a new class that they all share. (One thing can have many classes, for example ```class="quickpic1 button" means it has 'quickpic1' class and 'button' class).
  • add some CSS hover effects so the buttons look different when the mouse is over them, so the user can tell they are buttons.

Change ideas into objects, not strings, so we can save more info about each idea

background

On the server, whenever an idea is saved, we want to save extra info like:

  • who posted the idea
  • what time it was posted
  • maybe a picture was posted too
  • maybe the number of Likes or Reblogs the idea has

To support this, we need to change ideas from being a string to being an object.

A string is a sequence of letters - like a word, a sentence, or a paragraph.

here are some example strings

var string = "hello, i am a string";
var string2 = "i am another string";
var string3 = "a";
var string4 = ""; //this is an empty string!

An object, in JavaScript, is a bit like a filing system or a dictionary or a phone book. It can have lots of values and each value is filed under a certain label. Programmers call these "name-value pairs" because each value has a name.

var obby = {}; //create an empty object
obby.rating = 10; //created a name-value pair: the name is rating and the value is the number 10
obby.greeting = "hello, i am a string"; //the name is greeting and the value is a string

Act 1:

You will need to change the data structure a bit, so each idea an object, not just a string.

Look in index.js at the line that pushes the example idea onto the list of ideas.
At the moment, it pushes a string.

coolIdeas.push("Two cats who solve crimes in Dunedin");

Replace that line with this:

var idea = {};
idea.text = "Two cats who solve crimes in Dunedin";
coolIdeas.push(idea);

Now we are pushing an object.

Act 2: Displaying the idea again

If you look at the ideas feed, the example idea won't look good any more (remember you'll need to restart the server because you've changed index.js). In feed.html, we need to change the code to display the idea.text instead of the whole idea.

  • in feed.html, the idea will now display as [Object object]. You will need to tell the page to display the text value of the object. Basically, wherever it adds idea to the page, change it to add idea.text instead.

Act 3: posting ideas

If you try posting an idea and looking at the feed, that's broken now :/

That's because the ideas you post are still just a string, not an object.

In index.js currently, we get the value req.body.idea which is a string, and save it straight into the coolIdeas list

Instead, we are going to create a new empty object, then put that value in it as the .text field, then save it. Like this:

//delete this: -> coolIdeas.push(req.body.idea); //save a new idea
//add this:
var idea = {};
idea.text = request.body.idea;
coolIdeas.push(idea);
  • test that the feed.html now works like it used to, displaying the example idea and the user-posted ideas properly.

Commit your changes. Check everything works!

Act 4 - saving additional information

Now we can add other information to the ideas.

  • When an idea is saved on the server (index.js), as well as saving the text, create a new name-value pair with idea.time = 0;
  • test that it's working: in your web browser, go to http://localhost:3000/ideas and look at the raw list of ideas. You should see that each idea now has a time as well as a text.
  • Instead of always setting the time to 0, get the actual time - try googling "How to get current time javascript"

Put links on every page so it's easy to navigate between pages

As a user, I don't like having to remember all the URLs and type them in by hand.

I'd like to be able to click on links to get to every page on the site, and never get stuck on a page with no links.

  • Make some HTML to add a list of links to all the pages in the site
  • Add CSS to the style.css file to make the links appear as a bar going across the page instead of a list going down the page. You may need to put the links in a div with a new class, i.e. <div class="nav-bar">
  • Add the HTML to every page
  • check it works on every page

(This is often called the 'navigation bar' or 'nav bar')

Notes

this is what a navigation bar looks like

screen shot 2015-08-20 at 1 20 13 pm

I googled 'how to make a navigation bar' and got this page
http://www.w3schools.com/css/css_navbar.asp

Note: Links have a built in style that makes them blue. To change their color in the navbar, you'll need to make a more specific style that overrides it. For example, if your navbar has class="navbar", this rule will change the color of the links inside it:

.navbar a {
    color: pink;
}

That rule applies to links <a> that are inside something that has class="navbar"

Display each post's time

**This task can only be done after #4

ACT 1

Now that ideas are objects we can add other information to the ideas.

  • When an idea is saved on the server (index.js), as well as saving the text (idea.text), create a new name-value pair with idea.time = "test";
  • Restart you server and test that it's working: in your web browser, post some new ideas, then go to http://localhost:3000/ideas and look at the raw list of ideas. You should see that each idea now has a time as well as a text.
  • Instead of always setting the time to "test", get the actual time - try googling "How to get current time javascript"
  • There are two places in index.js where you need to set idea.time - once for the example idea that's created at the start, and once for the code when a user creates an idea. Make sure you've done both cases.
  • Now In feed.html add the idea.time so it displays after the idea text (note: it will need to be between the <h2> </h2> tags). After this change, when you look at http://localhost:3000/feed.html you should see the time for each post - but it's not pretty yet.

ACT 2

Right now, it looks like this: 2015-09-09T03:42:18.991Z. Only good if you are a robot ๐Ÿค–

We can make that nicer, but it will take a lot of code. Fortunately, someone else has already written the code for us! I found a plugin that will work, it's called jquery-dateFormat.

  • Include jquery-dateFormat by adding this line to the head section of feed.html

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-dateFormat/1.0/jquery.dateFormat.js"></script>

(It should go just below the other <script> line in the head section)

Now we have jquery-dateFormat, we can use some new commands. The full documentation is at https://github.com/phstc/jquery-dateFormat, but I pulled out the interesting parts for you here:

  • to display the post time nicely, replace idea.time with this:

$.format.prettyDate(idea.time)

  • check that your times are now pretty! They should say something like "11 minutes ago"

This is a good time to commit your changes

ACT 3

It's kind of confusing that the time is the same color as the text and author name.

Let's give the time its own html tag, with a class so we can give it a different CSS styles.

In feed.html, in the javascript, You will need to add an opening tag before the time, and a closing tag after the time.

  • Add <div class='time'> before the time value, and </div> after the time value.

Because we're writing in javascript, not in real HTML, we need to put the HTML tags inside speech marks so they become a string. (They will turn green in the Atom text editor.) Also, the string needs to be connected to the time with a plus in between.

  • Add a css rule to style.css that makes the time display in a different colour.

Check the feed to see that the time is now in a different colour.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.