Introduction to Javascript

Iain Nash / LavaLab 2014

What is Javascript?

  • Language of web browsers, the internet
  • Called (formally) ECMAScript
  • Has a builtin DOM and flexible datatypes
  • Based on prototype inheritance, hybrid language

JS <3 HTML

What can js do?

(hint: almost anything)

things relying on javascript:

this slideshow
facebook

google search

embed js locally

embed remote js

<!DOCTYPE HTML>
<html>
<head>
<title>hi js!</title>
</head>
<body>

<script type="text/javascript">
document.body
  .style.backgroundColor = 'red';
</script>
</body>
</html>
<!DOCTYPE HTML>
<html>
<head>
<title>hi js!</title>
</head>
<body>

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$('body').css('background','red');
</script>

<!-- 
Embed Remotely:
<script src="SCRIPT_SRC_HERE"></script> -->

</body>
</html>

Functions are Data

function withFiveMore(input){
  return input() + 5;
}
function rand(max){
  return Math.floor(Math.random()*max);
}
var print = function(t){
  console.log(t);
}

var getRandomNumber = function(){
  return rand(10);
}

print(withFiveMore(getRandomNumber));

Data structures

  • Fundamental components of programming.
  • Store information you manipulate in code.
  • Concepts shared across programming languages
  • Javascript is [untyped]
    • no type checking / compiling

Important JS data structures

list: [1,2,3,4]

dictionary: {'age': 14, 'name': 'teenagecoder'}

number:

  (int= no decimal) 12

  (float= has decimal) 12.434

string: 'this'

function: function() { alert('123'); }

common
builtin
functions

iMoprtant Built-in JS Functions

  • console.log(msg) - prints to the web console
  • alert(msg) - opens a dialog box
  • prompt(msg) - prompts for input
  • 'stri.ng'.split('.') -> ['stri','ng'] - splits string
  • [1,2,3].join('-') -> '1-2-3' - joins string
  • [1,2,3].indexOf(1) -> 0 - finds an array element
  • [1,2,3].append(2) -> [1,2,3,2] - adds an element

Let's get coding!

Subtitle

Right-click on any page element and select Inspect Element.

Open a Web Console

HTML Dom Functions

  • document.getElementById('id') - gets element by id="ID"
  • element.innerHTML = 'changes html inside element'
  • element.style.backgroundColor = 'red'
    • changes background color
  • element.addChild(otherElement) - adds an element inside an element

Demo time!

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Lavalab About</title>
</head>
<body>
  
  <div id="content">
    <div id="about"></div>
    <div id="mission"></div>
  </div>

<script>
function updateEl(el, text){
  document.getElementById(el).innerHTML = text;
}
function test(fb_data){
  updateEl('about', fb_data.about);
  updateEl('mission', fb_data.mission);
}
</script>
<script src="http://graph.facebook.com/LavaLabUSC?callback=test"></script>
  
</body>
</html>

Whats the weather?

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Weather</title>
</head>
<body>
  
  <div id="content">
    <div id="weather"></div>
    <div id="temp"></div>
  </div>

<script>
function updateEl(el, text){
  document.getElementById(el).innerHTML = text;
}
function test(weather){
  updateEl('weather', weather.weather[0].description);
  updateEl('temp', weather.main.temp);
}
</script>
<script src="http://api.openweathermap.org/data/2.5/weather?q=los%20angeles&callback=test"></script>
  
</body>
</html>

Case study

shouldiwearpantsotday.tk

<!DOCTYPE HTML>
<html>
<head>
	<style>
		#answer {
			margin-top: 20%;font-size: 10em;
			text-align: center;font-family: Helvetica;font-weight: bold; }
	</style>
	<script>
		function fubar(data){
			var scr = document.createElement('script');
			scr.src = 'http://api.openweathermap.org/data/2.5/weather?lat='+
data.latitude+'&lon='+data.longitude
+'&callback=blahblah';
			document.body.appendChild(scr);
		}
		function kelvintofarenheit(kelvin){
			return (kelvin - 273.15)* 1.8000 + 32.00;
		}
		function deal_with_temp(temp){
			var answer;
			if (temp <= 66){
				answer = 'YES';
			} else {
				answer = 'NO';
			}
			document.getElementById('answer').innerHTML = answer;
		}
		function blahblah(weather){
			deal_with_temp(kelvintofarenheit(weather.main.temperature));
		}
	</script>
	
</head>
<body>
	<div id="answer">...</div>
	<script src="http://freegeoip.net/json/?callback=fubar"></script>
</body>
</html>

frameworks:
angular
jquery

react

Why frameworks

They cut down on repetitive code.

Encourage better code organization

Overall, they make life easier.

some frameworks

jquery - dom manipulation / animation / data transport library

 

angular.js - data binding / transport library (for apps)

 

react.js - templating binding library

jQuery

<!DOCTYPE HTML>
<head>
<title>Instagram Demo</title>
<style>
	.img {	width: 300px;	height: 300px;display: inline-block;}
</style>
</head>
<body>
	<h1>Latest Photos</h1>
	<div id="photos">

	</div>
	 <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
	 <script type="text/javascript">
	 	$(function() {
	 	$.getJSON('http://api.tumblr.com/v2/tagged?tag=gif&api_key=fuiKNFp9vQFvjLNvx4sUwti4Yb5yGutBN4Xh10LXZhhRKjWlV4&callback=?', function(tumblr_data) {
	 	console.log(tumblr_data);
	 	var images = tumblr_data.response;
	 	for (var i = 0; i < images.length; i++) {
	 		var image_url = images[i].photos[0].original_size.url;
	 	$('<div class="body" style="background-image:url(' + image_url + ');background-size:cover;"></div>').appendTo('#photos');
	 	}
	 	});
	 	});
	 </script>
</body>

Introduction to Javascript

By Iain Nash

Introduction to Javascript

  • 1,845