Syllabus

Coding For Rookies

Course Goals: To learn beginner level programming fundamentals, design and user experience basics, and how to build interactive websites efficiently and with modern best practices, and to discover ways that these technologies can be used in other applications apart from the Web.

Introduction to the Internet:

  • Logistics and introductions
  • Set up your development environment
    • Download, install, and configure Chrome
    • Download, install, and configure Atom
  • Your first website
    • “Hello World!”
  • How the web works
    • Brief history of the internet/web
      • Origins of programming, computing
      • W3C, ICANN, etc.
    • Brief overview of web architecture
      • Protocols (http, ssh, ftp)
      • Request/Response cycle
    • Hosting and DNS
      • Site44
      • iwantmyname

HTML:

  • HTML
    • Elements, tags, forms, links, structure, etc.
    • Attributes, content, hierarchy
  • Bootstrap
    • CDNs
    • Classes, introduce CSS
    • Documentation
  • Build a basic website
    • Formspree

CSS:

  • Basic UX principles and best practices
    • “Above the fold”
    • Simplicity
    • Colors
    • Patterns
  • CSS
    • Relationship to HTML
    • Cascades
    • Preprocessors
    • Selectors
    • Rules
    • Properties
  • Custom Styling
    • CSS Animations
  • Build a website with what we’ve learned

JavaScript:

  • JavaScript
    • Logic
    • Data Structures
    • Algorithms
    • Functions
  • Build a little game

jQuery and Dynamic Data:

  • jQuery
    • DOM traversal
    • Selecting and manipulating elements
    • Ajax
  • APIs
  • Build an app that hits a backend

Beyond the Web:

  • Using JS for native mobile (react native, phonegap)
  • Using JS for native desktop (electron)
  • Applying knowledge to other languages and domains
  • Web games, Elm and other languages, etc.
  • Wrap up, review, and resources

Introduction to the Internet

Setting up our development environment and creating our first website

  1. Download and install Google Chrome

    • Right click anywhere in the page and choose the “Inspect” option.

      • You can click around and look at the code for what is creating the stuff on the site. This is how people learned how to create web pages in the early days - by looking at how other people did it first.
    • Right click anywhere in the page and choose the “View Page Source” option.

      • This is not as interactive as “Inspect,” but gives a full high level overview of how a web page is structured.
    • We will go over the dev tools more as we progress through the class.

  2. Download and install the Atom text editor

    • Text editors are like word processors, but for code. They are useful for editing and reading all types of code, and there are many different editors. We are using Atom for a number of reasons, mainly it’s easy set up and learning curve.

    • Poke around the settings a bit, and select Packages then search for “autosave.” Click the option that comes up, and look for the “enable” checkbox and check it. Now your files will save whenever you leave the window! Feel free to install other themes and packages you like if you feel like it.

    • Check out their flight manual for more information about Atom and how to use and customize it.

  3. Create a new directory (aka folder) on your desktop or somewhere you can easily access it. Name it “week1” or something similar.

    • In Atom, go to File > Add project folder then find and select your newly created week1 folder. When you see the folder in the left section, right click it and select “New file.” Name the file “index.html,” and open it.

    • Type “Hello World!” in the file, save it, and double click the file in the location you created it. It should open up in Chrome, and now you’ve created your first website!

    • But, it’s not exactly proper HTML. Lets add an HTML tag so the browser can make more sense of it.

1
<h1>Hello World!</h1>
  • Save it, and reload your browser. It should be big and bold.

  • Now we need to add the bones of the structure of an HTML page that will make it work online. Go to html5-boilerplate and look at the code there. We only need to use a few pieces of this for our site.

1
2
3
4
5
6
7
8
9
10
11
12
13
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Coding For Rookies</title>
<meta name="description" content="Coding for rookies Lifelong Learning U of U">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Hello world! This is Coding for Rookies.</h1>
</body>
</html>
  • Now you have your first real website.

History of computing and the Internet

  • The history of computing, begins with the first programmer, Ada Lovelace, and the first “computer,” Charles Babbage’s Analytical Engine which Ada conceptualized the idea of programming for over snail-mail correspondence in the early 1800s. Alan Turing brought the idea back to life in the 1930s.

    • Computers started gaining traction in the WWII era while funding was abundant and were the size of rooms and used vacuum tubes until transistors became mass produced.

    • History of the Internet and World Wide Web started with their precursors like ARPANET in the 1960s and 1970s, and remarked on how the University of Utah played a vital role in the birth of the internet by being one of it’s first four computer network nodes.

      • The difference between the Internet and the World Wide Web is important to note. The Web exists in the Internet among a number of other things like email, file sharing, and others.
      • Tim Berners-Lee is credited as the inventor of the World Wide Web in 1989 and Hyptertext some years before that. He also built the first web browser and the first web site went online in 1991.
      • Tim also created HTML and HTTP, two important backbones of the Web.

Governing bodies of the Internet

  • There are several governing bodies of the Internet that operate globally and keep things moving smoothly and within standards.
    • Two of the most powerful governers are ICANN, which controls the naming of domains and their IP addresses, and the W3C, which is led by Berners-Lee and creates and regulates the standards of the World Wide Web, including which languages and styles are used and read by browsers and how these evolve.

Relationship between hardware and software

  • When we write code for the Web, we are basically going several levels of abstraction above the hardware, with the programing language eventually telling the circuits when and where to allow the electrical pulses through. This is what binary (1s and 0s) is, 1 means allow the electrical pulse through (on) and 0 means don’t (off).
    • These electrical pulses decide what your machine does from saving form data from a web page to flicking on the right pixels on your monitor.

How the Internet and Web work

  • The Web’s architecture is built around a Request-Response cycle, in which a client (in our case a browser or user) makes a request to a server - like to get a URL of your friend’s Facebook profile page, and then the server sends back a response - like returning the HTML code of your friend’s Facebook profile page.

Hosting and DNS

  • Site44

    • If you want to host your projects for the class, set up a Dropbox account and then try out the free trial of Site44. All you have to do is follow the instructions given, which mainly consist of replacing the index.html file in the newly created Site44 folder in your Dropbox.
    • There are many other ways to host web pages, but this is among the easiest.
  • iwantmyname

    • If you want to purchase custom domain names, I recommend iwantmyname. You can easily hook it up to hosting services like Site44 to route to your domain, among other apps you might need in the future.

Extra resources

  • My favorite computer history book is The Innovators by Walter Isaacson. It is a fantastic biography of many of the biggest names in computing.

  • Learn more about the Chrome Developer Tools by checking out this Code School tutorial. This is something you can do one lesson at a time keeping up with the class if you’re interested.

HTML

HTML

  1. Create a new folder called “week2” and open it up in Atom by selecting File > Add project folder. Then create a new file in that folder by right-clicking it and selecting “New file.” Name the file “index.html” and select it.

    • Copy the HTML from last week (at the end of step 3 in the previous article) and paste it into the new file.
  2. Now we will introduce some new HTML tags. First, lets look at the <img> tag, which is for images. <img> elements don’t require a closing tag because they can’t have any content, since all their information is contained within it’s attributes. Let’s put an image on our page right below the <h1> tag:

1
<img src="http://placekitten.com/1000/300" alt="Kitten" />
  • The src attribute is the source of the image we want. It can be within our website directory, or a URL from somewhere else on the web like in our case where we get a placeholder image from placekitten.com. The numbers in that URL correspond to the width and height of the image respectively.

  • The alt attribute is the alternate text that would show up if the image couldn’t be found or is broken, and what screen readers will use to read instead of the image.

  • Save and reload your page. You should see a cute kitten!

Emmet

  • Before we move on, lets add another useful package to Atom. From the menu bar, select Atom > Preferences, then click “install” on the tree in the left. Search for “Emmet,” and click “install” when it pops up.

  • Now when you start typing the name of an HTML tag (without it’s first bracket), a little popup will show next to the cursor and you can click the item that shows up or press “enter” to have the element autocomplete. This is super useful to speed up writing your HTML. It will autocomplete many of the common attributes in the tags, so stick to the following examples to remove or add attributes as necessary.

Forms

  1. Below our new <img> tag, lets create a web form. We’ll put a few input fields in there, and post the form to a back end - which will be our own email in this case - using formspree which will be the value of the action attribute:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<form class="" action="https://formspree.io/your@email.com" method="post">
<label for="firstName">Name:</label>
<input type="text" name="firstName" value="">

<label for="email">Email:</label>
<input type="email" name="email" placeholder="your@email.com" value="">

<label for="subject">Subject:</label>
<input type="text" name="subject" value="">

<label for="textarea">Message:</label>
<textarea name="textarea" rows="8" cols="40"></textarea>

<button type="submit" name="button">Submit!</button>
</form>
  • There are many different form elements in which a user can input information. We are focusing only on a few to keep it simple.

    • The <label> tag names our <input>s and it’s for attribute corresponds with the <input>‘s name attribute.
  • Save and reload your page. You should see a form with a button under the kitten.

    • Notice the email field will validate that there is an @ symbol, or it will show an error. This is because the <input> tag’s type attribute specifies that it is an email field.
Posting the form
  • If you have Site44 set up as shown in the last part of the notes for Week 1, you can create a new site in it and replace the index.html file in that folder with the one in week2 which you’re working in.

    • Now fill out the form and click submit. You should receive an email at the address in the action attribute with the form contents!
  • You can try submitting the form even if the site isn’t hosted, but it will take you to a page that says it needs to be online in order to work. If you get that far you know you did it right anyway.

Bootstrap

  • Time to make our page look like a real web page and improve the ugly default styling.

  • We are going to use a CDN (content delivery network) to link a useful stylesheet framework called Bootstrap to our page.

    • Google search “bootstrap cdn” and click the first link. Then, under “Complete CSS,” click the arrow dropdown. Copy the long <link> tag in the field under the “HTML” portion. Paste this tag at the bottom of your <head>, just above the closing </head> tag and below the last <meta> tag, so it looks like this:
1
2
3
4
5
6
7
8
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Coding For Rookies</title>
<meta name="description" content="Coding for rookies Lifelong Learning U of U">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
  • Now we will add a few <div> wrapper elements and apply some class attributes throughout our page to improve the styling.

    • First, wrap the entire content of the <body> into a “container,” with <div class="container"> at the top and the closing </div> tag at the bottom of the <body>. This will give nice margins to our page.
    • Find the “Forms” section in Bootstrap’s documentation, and look at the example. The nice fonts, softened inputs with focus highlights, etc. Thats what we want our form to look like, so we’ll implement the elements and class names around the elements as shown in the example.
    • Find the “Buttons” section and lets add class="btn btn-primary" to the <button> element to make it more prominent. The type="submit" implicitly tells the form to run it’s action attribute.
    • Finally, lets wrap our 2 elements above the <form> into a class="jumbotron" to separate them from the page with some color contrast and font changes.
  • Now your entire page should look something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Coding For Rookies</title>
<meta name="description" content="Coding for rookies Lifelong Learning U of U">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="jumbotron">
<h1>Hello world! This is Coding for Rookies.</h1>
<img src="http://placekitten.com/1000/300" alt="Kitten" />
</div>
<form action="https://formspree.io/your@email.com" method="post">
<div class="form-group">
<label for="firstName">Name:</label>
<input type="text" class="form-control" name="firstName" value="">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" name="email" placeholder="your@email.com" value="">
</div>
<div class="form-group">
<label for="subject">Subject:</label>
<input type="text" class="form-control" name="subject" value="">
</div>
<div class="form-group">
<label for="textarea">Message:</label>
<textarea class="form-control" name="textarea" rows="8" cols="40"></textarea>
</div>
<button type="submit" class="btn btn-primary" name="button">Submit!</button>
</form>
</div>
</body>
</html>
  • Go ahead and play around with this and try implementing some more tags and seeing if you can get them to submit to your email.

Extra resources

  • My favorite book on HTML (and CSS) is HTML & CSS by John Duckett. If you read this entire book back to front, and do the exercises along the way, you’ll have an excellent foundation in these languages.

  • If you want a more extensive introduction to HTML, try out the course on FreeCodeCamp. This is a wonderful free online course that is far superior to others like Codecademy, but don’t hesitate trying others too.

  • Learn more about how HTML forms work by reading this article.

CSS

Intro to CSS

  1. Create a new folder called “week3” and open it up in Atom by selecting File > Add project folder. Then create a new file in that folder by right-clicking it and selecting “New file.” Name the file “index.html” and select it.
    • Copy the HTML from week 1 and paste it into the new file.
  2. Create another new file in the same folder called “styles.css,” and leave it blank for now.
    • Now link the CSS file to the HTML file by adding the line <link rel="stylesheet" href="styles.css">
      just before the closing <head> tag.
  3. We are going to be switching between both files quite often which is common for development. Keep both files open in Atom, and create a <header> element inside the body, and fill it in with the navigation structure we see in most websites.
1
2
3
4
5
6
7
8
9
<header>
<nav>
<img src="http://placekitten.com/60/60" alt="logo" />
<ul>
<li><a href="#about">About</a></li>
<li><a href="http://google.com">Google</a></li>
</ul>
</nav>
</header>
  • We are introducing semantic tags which help with user accessibility and developer readability, so we know exactly what each tag in the structure means.
  • Here we have created a navigation with a logo image (pulled from Placekitten.com) and an unordered list with a couple links - one that links internally on the same page and another that links externally to Google.

Cross-browser compatibility

  1. Now lets go back to the CSS file. First we will do a couple boilerplate styles to our page that will help it stay consistent across different browsers.
1
2
3
4
5
6
7
* {
vertical-align: top;
}

body {
margin: 0;
}
  • These styles ensure that all elements start their content at the top of the element which isn’t always default in every browser, and that there is no default margin around the body causing unwanted whitespace bordering the page.
  • This is a minimal version of what is known as a CSS reset.

Anatomy of a CSS rule

  1. Each style block in CSS is called a rule. A rule starts with a selector followed by a declaration which is denoted by the curly braces {}. Inside the declaration are properties with values.

  2. Lets style the header we created in the HTML. In your CSS file under the body declaration:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
header {
height: 80px;
background-color: #3498db;
padding: 10px;
}
header img{
border-radius: 50%;
}
header nav, header ul, header li {
display: inline-block;
}
header li a{
padding-left: 20px;
}
  • When we have more than one selector listed next to each other, we are using CSS’s specificity to drill into exactly the element that is nested inside the previous selector and style that.
  • When we have commas between selectors, we are telling CSS to apply the style to each individual selector separated by the commas.
  • Add each property one by one, and save and reload your page to see the styles being applied so you get the feel of what each one does.
  • A good place to find colors for CSS is at flatuicolors.com. CSS defines most colors in hexadecimal, and this is a nice place to see a color and copy the code for it. Choose any color and paste it in the background-color property of the header rule.

Building and styling the rest of our page

  1. Add a banner section to our page with a fun little style gimmick called parallax.
  • Add the following HTML underneath the closing </header> tag:
1
2
3
<section class="banner">
<h1>Mike's Cool Website!</h1>
</section>
  • And the CSS underneath the header styles from above:
1
2
3
4
5
6
7
8
9
10
11
section.banner {
padding-top: 150px;
height: 300px;
background: url("http://placekitten.com/500/500") fixed;
background-size: cover;
}
h1{
color: white;
font-size: 72px;
text-align: center;
}
  • Since our section has a class of “banner” we can use that as a selector with the “dot notation” (like section.banner) in our CSS.
  • The background url is just a Placekitten image which we fix to the background of the section allowing for other content to scroll over it creating our parallax effect.
  1. In order to see the effect, we need to add more content. Lets add the About section to our page underneath the previous banner section we created:
1
2
3
4
<section id="about">
<p>Occupy meggings subway tile poutine, bitters slow-carb trust fund XOXO master cleanse venmo. Occupy fap etsy, pour-over brooklyn snackwave blue bottle VHS. Helvetica marfa brooklyn, pok pok deep v hammock +1 actually mlkshk lomo swag activated charcoal cliche ethical selfies. Yr taxidermy austin pop-up salvia, sustainable asymmetrical kickstarter wayfarers plaid succulents craft beer jean shorts. PBR&B affogato air plant, art party umami kickstarter heirloom literally letterpress biodiesel blue bottle next level. Truffaut retro man bun, fap unicorn jianbing blog franzen tacos keytar tumeric pug meditation beard cliche. Fap keffiyeh mlkshk drinking vinegar, chillwave hella prism put a bird on it neutra readymade tbh forage deep v microdosing cold-pressed.
</p>
</section>
  • I got that placeholder text from hipster ipsum, a silly take on Lorem ipsum which has been used as placeholder text for design purposes since time immemorial.
  • Notice the id of “about” in this section - this will correspond to our anchor tag (hyperlink) from the header section where we use the id notation (like #about), and the click of that link will bring you to this section.
  • Lets style that section. Since we only have one p tag in our page, we don’t have to specify what it’s HTML parent is for illustration purposes, although it is good practice to do so.
1
2
3
4
p {
margin: 5%;
text-align: center;
}
  1. Lets build out the footer section of our page.
1
2
3
<footer>
<h1><a href="tel:1-800-call-me">1-800-Call-Me</a></h1>
</footer>
  • Notice the semantic tag footer as has been our habit throughout this page.
  • The href attribute of the a tag here is not a web hyperlink, but we let the browser know that it is a telephone number by the “tel:” prefix. Open this page on your phone if you’re hosting it, and you should see that link takes you to dial out at that number.
  • Style our footer now:
1
2
3
4
5
6
7
8
footer {
height: 170px;
background-color: #3498db;
padding: 10px;
}
footer a {
font-size: 50px;
}
  • Use the same background color as the header for consistency, and a contrasting color for the font.
  1. Final touches
  • We can use a couple more styles that will help with user experience, like a better font throughout the page and a way to know what text is hyperlinked.

    • In the body declaration, add font-size: 22px; and font-family: 'Helvetica', sans-serif; for a nicer default font.
    • At the bottom of the CSS file, add 2 new rules:

      1
      2
      3
      4
      5
      6
      7
      8

      a {
      color: #f1c40f;
      text-decoration: none;
      }
      a:hover {
      color: gray;
      }
    • The :hover is a psuedo-selector which reacts to a user behavior, and we want it on all the a tags.

  1. Your final HTML file should look something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Best Home Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<nav>
<img src="http://placekitten.com/60/60" alt="logo" />
<ul>
<li><a href="#about">About</a></li>
<li><a href="http://google.com">Google</a></li>
</ul>
</nav>
</header>
<section class="banner">
<h1>Mike's Cool Website!</h1>
</section>
<section id="about">
<p>
Occupy meggings subway tile poutine, bitters slow-carb trust fund XOXO master cleanse venmo. Occupy fap etsy, pour-over brooklyn snackwave blue bottle VHS. Helvetica marfa brooklyn, pok pok deep v hammock +1 actually mlkshk lomo swag activated charcoal cliche ethical selfies. Yr taxidermy austin pop-up salvia, sustainable asymmetrical kickstarter wayfarers plaid succulents craft beer jean shorts. PBR&B affogato air plant, art party umami kickstarter heirloom literally letterpress biodiesel blue bottle next level. Truffaut retro man bun, fap unicorn jianbing blog franzen tacos keytar tumeric pug meditation beard cliche. Fap keffiyeh mlkshk drinking vinegar, chillwave hella prism put a bird on it neutra readymade tbh forage deep v microdosing cold-pressed.
</p>
</section>
<footer>
<h1><a href="tel:1-800-call-me">1-800-Call-Me</a></h1>
</footer>
</body>
</html>
  • And the CSS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
* {
vertical-align: top;
}
body {
font-size: 22px;
font-family: 'Helvetica', sans-serif;
margin: 0;
}
header {
height: 80px;
background-color: #3498db;
padding: 10px;
}
header img {
border-radius: 50%;
}
header nav, header ul, header li {
display: inline-block;
}
header li a {
padding-left: 20px;
color: black;
}
section.banner {
padding-top: 150px;
height: 300px;
background: url("http://placekitten.com/500/500") fixed;
background-size: cover;
}
h1 {
color: white;
font-size: 72px;
text-align: center;
}
p {
margin: 5%;
text-align: center;
}
footer {
height: 170px;
background-color: #3498db;
padding: 10px;
}
footer a {
font-size: 50px;
}
a {
text-decoration: none;
color: #f1c40f;
}
a:hover {
color: gray;
}

Basic user experience principles

JavaScript

Download the boilerplate:

Click this link to get the boilerplate files

  • Open the downloaded folder in Atom and look through the files. You’ll see some HTML and CSS already set up, and an empty JS file.
  • Look through the HTML and CSS for a review, and open the file in Chrome to see what it looks like.
  • Open the JS file in the boilerplate you downloaded and write console.log('Hello world!') then save it and reload your browser, then open up the chrome dev tools and select “console” from the right pane. You should see your first JavaScript program!

JavaScript

Intro to JS
Number guessing game
  • Copy this one piece at a time into your JS file. Try to see what each line does, and play around with the game. See what other things you can do with this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// I'm a comment!
var answer = Math.ceil(Math.random() * 50);
var form = document.querySelector('form');
var input = document.querySelector('input');
var response = document.querySelector('.response');
var response = $('.response')
console.log(answer);

document.addEventListener('submit', checkGuess);

function checkGuess (event) {
event.preventDefault();
var guess = input.value;
if (guess == answer) {
response.textContent = guess + " is correct!";
form.style.backgroundColor = "#27ae60";
} else if (guess > answer + 10) {
response.textContent = guess + " is WAY too high!";
form.style.backgroundColor = "#f39c12";
} else if (guess > answer) {
response.textContent = guess + " is too high!";
form.style.backgroundColor = "#f39c12";
} else if (guess < answer - 10) {
response.textContent = guess + " is WAY too low!";
form.style.backgroundColor = "#f39c12";
} else if (guess < answer) {
response.textContent = guess + " is too low!";
form.style.backgroundColor = "#f39c12";
} else {
response.textContent = guess + " is not a number!!!!";
form.style.backgroundColor = "#c0392b";
}
}

Next week

JS Data Structures and Algorithms

jQuery and Dynamic Data

Spotify Playlist Creator!

index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Coding for Rookies Playlist Creator</title>
</head>
<body>
<h1>Playlist Creator!</h1>
<form>
<input type="text" id="search">
<button id="create">Create Playlist!</button>
</form>
<div id="results"></div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="app.js"></script>
</body>
</html>
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
$("#create").click(function(event){
event.preventDefault();
createPlaylist();
});
function createPlaylist() {
var artistName = $("#search").val();
getArtists(artistName);
function getArtists(artist) {
$.ajax({
url: 'https://api.spotify.com/v1/search',
data: {
q: artist,
type: 'artist'
},
success: function(response){
var artistId = response.artists.items[0].id;
getRelatedArtists(artistId);
}
});
}
function getRelatedArtists(id) {
$.ajax({
url: 'https://api.spotify.com/v1/artists/' + id + '/related-artists',
success: function(response){
var artists = response.artists;
getTopTracks(artists);
}
});
}
function getTopTracks(artistsArray){
$.each(artistsArray, function(index, artist){
$.ajax({
url: 'https://api.spotify.com/v1/artists/' + artist.id + '/top-tracks?country=US',
success: function(response){
var trackObj = response.tracks[0];
console.log(trackObj);
displayTrack(trackObj)
}
});
});
}
function displayTrack(track){
$("#results").append("<p><a href='" + track.href + "'>" + track.artists[0].name + " - " + track.name + "</a></p>");
}
}