GDI Seattle - Intro to JavaScript Class 4

31
BEGINNING JAVASCRIPT CLASS 4 Javascript ~ Girl Develop It ~

description

Instructor: Dallas Tester

Transcript of GDI Seattle - Intro to JavaScript Class 4

Page 1: GDI Seattle - Intro to JavaScript Class 4

BEGINNING JAVASCRIPTCLASS 4Javascript ~ Girl Develop It ~

Page 2: GDI Seattle - Intro to JavaScript Class 4
Page 3: GDI Seattle - Intro to JavaScript Class 4

WELCOME!Girl Develop It is here to provide affordable andaccessible programs to learn software throughmentorship and hands-on instruction.Some "rules"

We are here for you!Every question is importantHelp each otherHave fun

Page 4: GDI Seattle - Intro to JavaScript Class 4

HTML FORMSHTML Forms allow users to enter information

Enter a nameI like popcorn

Favorite DinosaurTyrannosaurus Rex

Go!

Page 5: GDI Seattle - Intro to JavaScript Class 4

HTML FORMSHTML code for a form

<form action="serverSideHandler.aspx" id="about-me"> <input type = "text" id = "name" placeholder = "Enter a name"/> <input type = "checkbox" id="popcorn" />I like popcorn <label>Favorite Dinosaur</label> <select id = "dinosaur"> <option value = "t-rex">Tyrannosaurus Rex</option> <option value = "tri">Triceratops</option> <option value = "stego">Stegosaurus</option> <option value = "other">Other</option> </select> <input type = "submit" value = "Go!" style = "padding: 7px; font-size:1em"/></form>

Page 6: GDI Seattle - Intro to JavaScript Class 4

VALUES FROM FORMSYou can use JavaScript to get values from a form

Or set values of a form

var name = document.getElementById('name').value;document.write(name);

var popcorn = document.getElementById('popcorn').checked;document.write(popcorn);

name.value = 'Another name!';

popcorn.checked = true;

Page 7: GDI Seattle - Intro to JavaScript Class 4

FORM SUBMIT EVENTForms have a submit event.The submit event fires when a user clicks on a submitbutton or can be fired using the submit() method inJavaScript.Often, the submit event handler is used to validateinput before sending it to the server.

event.preventDefault() to prevent the form trying tosubmit to a server.

function submitHandler(event) { //Validate input values.

event.preventDefault();}var aboutMeForm = document.getElementById('about-me');

aboutMeForm.addEventListener('submit', submitHandler);

Page 8: GDI Seattle - Intro to JavaScript Class 4

LET'S DEVELOP ITChoose one of your functions made so far.Create a form to send dynamic data to the functionwhen you click the button.For example, take in the age, final age, and daily costfor the supply calculator.Don't forget to add parameters to your existingfunctions!<button id="calculate-supply" type="submit">Calculate Supply</button>

<form id="supply-calculator"> <label for="age">Age</label><input type="text" id="age" /> <label for="maxAge">Max Age</label><input type="text" id="maxAge" /> <label for="cost">Cost</label><input type="text" id="cost" /></form>

var ageInput = document.getElementById('age');var age = ageInput.value;

Page 9: GDI Seattle - Intro to JavaScript Class 4

LET'S ANSWER IT (SUPPLY CALCULATOR)<form id="supply-calculator"> <label for="age">Age:</label><input type="text" id="age" /> <label for="maxAge">Max Age:</label><input type="text" id="maxAge" /> <label for="cost">Cost:</label><input type="text" id="cost" /></form>

document.addEventListener("DOMContentLoaded", function() { var form = document.getElementById('supply-calculator'); form.addEventListener('submit', getFormValues); });

function getFormValues(event) { var ageInput = document.getElementById('age'); var age = ageInput.value;

var maxAgeInput = document.getElementById('maxAge'); var maxAge = maxAgeInput.value;

var costInput = document.getElementById('cost'); var cost = costInput.value;

calculate(age, maxAge, dailyCost); event.preventDefault();}

function calculate(age, maxAge, dailyCost) { ... }

Page 10: GDI Seattle - Intro to JavaScript Class 4

WARNINGThe following few slides have lots of acronyms and

jargon.On behalf of developers everywhere, we apologize

Page 11: GDI Seattle - Intro to JavaScript Class 4

WHAT IS AN API?Application Programming InterfaceData structure and rules for accessing an applicationHow we can access information from sites that arenot our own (GitHub, Twitter, Meetup, Facebook,Foursquare)Primary role: a channel for applications to worktogether

Page 12: GDI Seattle - Intro to JavaScript Class 4

WHERE DO I LEARN ABOUT AN API?All (good) APIs have documentation

GitHub ( )Facebook ( )Twitter ( )Meetup ( )FourSquare ( )

http://developer.github.com/https://developers.facebook.com/

https://dev.twitter.com/http://www.meetup.com/meetup_api/

https://developer.foursquare.com/

Page 13: GDI Seattle - Intro to JavaScript Class 4

ACCESSING APISMost APIs require an API Key

A what?API Key or Developer Key is a way for an API toidentify youMore secure for an API (Know who is using their API)More secure for you -- people can't pretend to beyour website

Not all APIs require a key!The APIs we'll be using today (GitHub) don't requirea key.

Page 14: GDI Seattle - Intro to JavaScript Class 4

WHAT IS AJAX?Asynchronous JavaScript and XMLMethod to communicate to a server or APIAsynchronous means:

I ask Twitter for all the tweets ever!That will take a whileMy whole website could be locked up while I wait!Or, my call can be 'asynchronous' and my websitewill just listen for Twitter's response with one ear,but go about normal business until the responsearrives.

Requests and results can be in JavaScript or XML

Page 15: GDI Seattle - Intro to JavaScript Class 4

WHAT IS REST?Representational State TransferREST is a way to ask an API for information by usinga URL.REST Urls are created with the following syntax:

http://ApiSite.com/method?parameter=value&parameter=valueMethod -- what you want from the API. Defined byAPI documentationsParameter -- a type of filter or restraint. Defined byAPI documentationsValue -- value for parameter. Defined by you!

Page 16: GDI Seattle - Intro to JavaScript Class 4

WHAT IS JSON?JavaScript Object NotationFormat for data returned from APIsYou've seen it before!JavaScript objects

{"status": "active","title": "Instructor","bio": "Hi, everybody! I'm an instructor for GDI. My teaching background spans from high school to the present. My professional background spans back-end, front-end, testing, and technical writing.","name": "Dallas Tester","group": { "id": 7208692, "name": "Girl Develop It Seattle", "urlname": "Girl-Develop-It-Seattle", "who": "Nerdettes" }}

Page 17: GDI Seattle - Intro to JavaScript Class 4

MAKING AJAX CALLS WITH JAVASCRIPTUse the XMLHttpRequest object built in to JavaScript

We're using the onreadystatechange event handler towait until the request is finished (readyState === 4) and

then log the JSON result to the console.

var serverRequest = new XMLHttpRequest(); serverRequest.onreadystatechange = function() { if(serverRequest.readyState === 4) { console.log(serverRequest.responseText); }}serverRequest.open('GET', 'URLToEndPoint', true);serverRequest.send();

Page 18: GDI Seattle - Intro to JavaScript Class 4

LET'S DEVELOP ITLet's make a call to GitHub's API.We will get all of the events for the Girl Develop Itorganization.Your API is here:https://api.github.com/orgs/girldevelopit/eventsvar serverRequest = new XMLHttpRequest(); serverRequest.onreadystatechange = function() { if(serverRequest.readyState === 4) { console.log(serverRequest.responseText); }}serverRequest.open('GET', 'URL', true);serverRequest.send();

Page 19: GDI Seattle - Intro to JavaScript Class 4

LET'S ANSWER IT!var serverRequest = new XMLHttpRequest(); serverRequest.onreadystatechange = function() { if(serverRequest.readyState === 4) { console.log(serverRequest.responseText); }}serverRequest.open('GET', 'https://api.github.com/orgs/girldevelopit/events', true);serverRequest.send();

[ { "id": "1837010532", "type": "WatchEvent", "actor": { "id": 3051672, "login": "celiala", "url": "https://api.github.com/users/celiala", "avatar_url": "https://2.gravatar.com/avatar/d22540938c49eba7da81d45fa1f0f245?d=https%3A%2…kamai.net%2Fassets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png" } ... }]

Page 20: GDI Seattle - Intro to JavaScript Class 4

WHAT IS A LIBRARY?Software libraries contain functions (not books).When you include a library, you can use all thefunctions in that libraryThat means: you get to take advantage of otherpeople's experience!And... Save time!

Page 21: GDI Seattle - Intro to JavaScript Class 4

WHAT IS JQUERY?jQuery is a library of JavaScript functions.

It contains many functions to help simplify yourJavaScript programming, including:

HTML element selection & manipulationCSS manipulationHTML eventsCalling APIs

Page 22: GDI Seattle - Intro to JavaScript Class 4

WHY USE JQUERY?The most popular JavaScript libraryjQuery empowers you to "write less, do more."Great Used by nearly 20 million websites

documentation and tutorials

Page 23: GDI Seattle - Intro to JavaScript Class 4

INCLUDING JQUERYTwo ways to include jQuery on your page:

Download the library, store it locally:

Include the the live library:

Note: live code can change so be aware when decidingon how you include the code.

<script type="text/javascript" src="jquery.js"></script>

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

Page 24: GDI Seattle - Intro to JavaScript Class 4

WHAT CAN JQUERY DO FOR ME?Remember document.getElementById() and

documet.getElementsByTagName()?jQuery makes it this easy:

Element name (div, p)

ID name (#mainpicture, #results)

Class name (.result, .picture)

var divs = $('div'); // All divs on page

var img = $('#mainpicture'); //img with id mainpicture

var images = $('.picture'); //All images with class picture

Page 25: GDI Seattle - Intro to JavaScript Class 4

WHAT CAN JQUERY DO FOR ME?Get and set attributes easily:

Get and set CSS properties:

Create elements:

Get and set the value (replaces innerHTML)

var img = $('#mainpicture');var imageUrl = img.attr('src');img.attr('src', 'http://www.website.com/newImage.png');

var imageWidth = img.css('width');img.css('width', '200px');

var newDiv = $('<div></div>');

var div = $('#results');var divHTML = div.html();div.html('<b>This is new HTML!</b>');

Page 26: GDI Seattle - Intro to JavaScript Class 4

WHAT CAN JQUERY DO FOR ME?Append and prepend text (no more createTextNode):

Simplify adding events...

...and the DOMContentLoaded event:

Data access is easy, too:

var div = $('#results');div.append('This is new text at the end!');div.prepend('This is new text at the beginning!');

var button = $('#calculate-button');button.click(function() { ... });

$(document).ready(function() { ... });

$.ajax({ url: 'https://api.github.com...', success: function(data) { //Event handler here }});

Along with a LOT more!

Page 27: GDI Seattle - Intro to JavaScript Class 4

LET'S DEVELOP ITInclude the jQuery library on your page. jquery.comhas a nice shortcut called Quick Access at the bottomof every page.Update your previous code to use $.ajax for theGitHub API call.jQuery returns an array of objects from this particularAPI. Utilize looping to get objects and output their idproperty.Feel free to play around with the other functionality ofjQuery.$(document).ready(function() { $.ajax({ url: 'https://api.github.com/orgs/girldevelopit/events', success: function(data) { //Do something with the data... } });});

Page 28: GDI Seattle - Intro to JavaScript Class 4

LET'S ANSWER IT$(document).ready(function() { $.ajax({ url: 'https://api.github.com/orgs/girldevelopit/events', success: function(data) { for(var i = 0; i < data.length; i++) { console.log(data[i].id); } //end for loop } //end success function }); //end AJAX call}); //end document ready call

Page 29: GDI Seattle - Intro to JavaScript Class 4

QUESTIONS?

Page 30: GDI Seattle - Intro to JavaScript Class 4

?

Page 31: GDI Seattle - Intro to JavaScript Class 4