BDI Logo

Introduction to JavaScript

Class 4

Let's Review

Two elephants interacting

Photo credit: Ginable cc

Anatomy of a website

Your Content
+ HTML: Structure
+ CSS: Presentation
= Your Website

A website is a way to present your content to the world, using HTML and CSS to present that content & make it look good.

HTML is Markup

Printed document covered in ink marks

Photo credit: Nic's events cc

CSS is Style

Fingernails with polka-dot paint job

Photo credit: pumpkincat210 cc

IDs vs. Classes

ID -- Should only apply to one element on a webpage, i.e., a webpage only has one footer.
The "#" is how you tell CSS "this is an id."

Class -- Lots of elements can have the same class, i.e., There can be many warnings on one webpage.
The "." is how you tell CSS "this is a class name."

Nesting

HTML elements "nest" inside one another

Russian nesting dolls

Photo credit: John K cc

The DOM Tree

We model the nested structure of an HTML page with the DOM (Document Object Model) Tree. The browser makes a "map" of all the elements on a page.

The DOM: Sample Code

<!DOCTYPE html>
<html>
  <head>
    <title>Test Page</title>
    <style>
      h1 {
        color: red;
      }
    </style>
  </head>
  <body>
    <h1>My Page</h1>
    <p>Hello World!</p>
    <img src="http://placekitten.com/g/200/300" alt="cat"/>
  </body>
</html>

The DOM: Sample Model

Simple DOM Tree

DOM Access

Your browser automatically builds a Document object to store the DOM of a page. To change a page:

  1. Find the DOM node and store it in a variable
  2. Use methods to manipulate the node

Finding Nodes

A magnifying glass

Photo credit: Jeffery Beall cc

DOM Access: By Id

You can find nodes by id using the method:

document.getElementById(id);

To find:

<img id="kittenPic" src="http://placekitten.com/g/200/300" alt="cat"/>

We would use:

var imgKitten=document.getElementById('kittenPic');

DOM Access: By Tag Name

You can certain types of HTML elements using this method:

document.getElementsByTagName(tagName);

To find:

<li>Daisy</li>
<li>Tulip</li>

We would use:

var listItems=document.getElementsByTagName('li');
for (var i=0; i < listItems.length; i++) {
  var listItem=listItems[i];
}

DOM Access: HTML 5

In newer browsers, you can use other methods too.

Available in IE9+, FF3.6+, Chrome 17+, Safari 5+:

document.getElementsByClassName(className);

Available in IE8+, FF3.6+, Chrome 17+, Safari 5+:

document.querySelector(cssQuery);
document.querySelectorAll(cssQuery);

getElement vs. getElements

Any method that starts with "getElement" will return a single node.

document.getElementById('uniqueID'); //returns a single node

Any method that starts with "getElements" will return a array of nodes. To modify a single node, you will need to use bracket notation to select the correct one.

document.getElementsByTagName('p'); //returns multiple nodes
var specficParagraph=document.getElementsByTagName('p')[2];

Changing Nodes

Red and yellow tulip

Photo credit: Darryl Kenyon cc

DOM Nodes: Attributes

You can access and change attributes of DOM nodes using dot notation.

To change this element:

<img id="kittenPic" src="http://placekitten.com/g/200/300" alt="cat"/>

We could change the src attribute this way:

var imgKitten=document.getElementById('kittenPic');
var oldSrc=imgKitten.src;
imgKitten.src='http://placekitten.com/g/600/500';

DOM Nodes: Getting and Setting Attributes

You can also use getAttribute/setAttribute

<img id="kittenPic" src="http://placekitten.com/g/200/300" alt="cat"/>

We could change the src attribute this way:

var imgKitten=document.getElementById('kittenPic');
var oldSrc=imgKitten.getAttribute('src');
imgKitten.setAttribute('src', 'http://placekitten.com/g/600/500');

DOM Nodes: Styles

You can change page css usingstyle

To make this CSS:

body {
  color: red;
}

Use this JavaScript:

var pageNode=document.getElementsByTagName('body')[0];
pageNode.style.color='red';

DOM Nodes: More Styles

Change any CSS property with a "-" to camelCase, and be sure to include a unit on any number

To make this CSS:

body {
  background-color: pink;
  padding-top: 10px;
}

Use this JavaScript:

var pageNode=document.getElementsByTagName('body')[0]
pageNode.style.backgroundColor='pink';
pageNode.style.paddingTop='10px';

Let's Develop It

Create a simple HTML page or use this sample code.

Isolate a node (an element on the page) and change an attribute or add a new style.

DOM innerHTML

Each DOM node has an innerHTML property with the HTML of all its children. You can use the property to view or change the HTML of a node.

For example, you can overwrite the entire body:

var pageNode=document.getElementsByTagName('body')[0];
  pageNode.innerHTML='<h1>Oh Noes!</h1>
  <p>I just changed the whole page!</p>'
  

Or just add some new content to the end

pageNode.innerHTML +='...just adding this bit at the end of the page.';
  

DOM innerHTML continued

You can also target a particular element

To fill this HTML element:

<p id="warning"></p>
  

We can select the node and modify it

var warningParagraph=document.getElementById('warning');
  warningParagraph.innerHTML='Danger Will Robinson!';
  

Creating New Nodes

The document object also provides ways to create nodes from scratch:

document.createElement(tagName);
  document.createTextNode(text);
  document.appendChild();
  

Creating New Nodes: Sample Code

var pageNode=document.getElementsByTagName('body')[0];

var newImg=document.createElement('img');
newImg.src='http://placekitten.com/g/500/200';
newImg.style.border='1px solid black';
pageNode.appendChild(newImg);

var newParagraph=document.createElement('p');
var paragraphText=document.createTextNode('Squee!');
newParagraph.appendChild(paragraphText);
pageNode.appendChild(newParagraph);

Let's Develop It

Create a new paragraph element and add it to a div on your page.

Events

Lego Magician

Photo credit: Eva Peris cc

Events

An 'event' is a type of object that is created when the user interacts with a web page.

For example, JS creates an event when a user clicks an element.

element.onclick=function () {
  //code to execute when the click happens
};

Types of Events

There are variety of events. Some of the most common:

  • onclick: The event occurs when the user clicks on an element
  • onmouseover: The event occurs when the pointer is moved onto an element
  • onkeyup: The event occurs when the user releases a key
  • onload: The event occurs when a document has been loaded
  • onfocus: The event occurs when an element gets focus

Events and Code

How do you make an event trigger some code?

  1. Break your code into functions
  2. Associate a function with a JavaScript event

Calling Functions from HTML

You can call a function directly from your HTML code:

<button id="clickMe" onclick="sayHi()">Click Me!</button>
function sayHi() {
  alert ('Hi!');
}

Listening Functions

Ear

Photo credit: Simon James cc

Listening Functions

Listening functions work like many of the other things we have done. First, find the object:

var myTarget=document.getElementById('clickMe');

Then add an event to that object:

myTarget.onclick=function(){
  alert ('Hi!');
}

Let's Develop It

Go back to the sample files you downloaded earlier.

Make some JavaScript code fire after an onmouseover event. Try adding the event to the HTML and adding a listening function.

Preventing Defaults

A cat resisting a bath

Preventing Defaults

Elements like buttons and links have a default behaviors. However, the event objects has a built-in method to handle that:

element.onclick=function (event) {
  event.preventDefault();
};

This

Lighted arrow sign pointed downward

Photo credit: Alan Berning cc

This

The keyword this references the element that the user has just interacted with

element.onmouseover=function (event) {
  console.log(this);
};

element.onclick=function (event) {
  this.style.backgroundColor='red';
  this.innerHTML='I've been clicked!';
};

Let's Develop It

Write code that targets this link:

<a href="http://girldevelopit.com/" id="gdiLink">Girl Develop It</a>

When a user clicks the link, the page should display an error message instead of going to the Girl Develop It homepage.

User Input

Comment box

Photo credit: Rym DeCoster cc

Forms

You can collect information from users to use in functions. The most common method is an HTML form

<form id="temperatureForm">
  <label for="temp">Temperature:</label> <input type="text" id="temp" size="3"/> degrees in
  <input type="radio" name="tempFormat" value="F" checked />Fahrenheit
  <input type="radio" name="tempFormat" value="C" />Celsius <br />
  <label for="submitButton"></label> <input id="tempSubmitButton" type="submit" value="Submit" />
</form>

Retrieving Form Data

You retrieve the values of form elements using the value method.

var temperature=document.getElementById('temp').value;
console.log (temperature);

You can retrieve the value of a form at any time. Try onblur (when a form element loses focus).

Radio Buttons

Radio buttons usually do not have IDs, so you will need to use an array:

var radios=document.getElementsByName('tempFormat');

for (var i=0, length=radios.length; i < length; i++) {
  if (radios[i].checked) {
    var radioButtonValue=radios[i].value;
    // only one radio can be checked, so stop now
    break;
  }
}

Submit buttons

If you are going to retrieve form values with the submit button, be sure to prevent the default action!

var submitButton=document.getElementById('tempSubmitButton');
  submitButton.onclick=function () {
  event.preventDefault();
  var temperature=document.getElementById('temp').value;
  console.log (temperature);
}

Let's Develop It

Collect a value from the input box on the page. Use it inside a function of some kind. For example, collect a number and multiply it by five or collect a name and display a greeting.

You did it!

Man jumping in air

Photo credit: sunface13 cc

Resources

Questions?