GDI logo

JavaScript for Beginners

Class 4

You Will Learn About:

  • Events
  • Listeners
  • Forms
  • DOM
  • DOM Methods
  • DOM Node Styles
  • Intro to JQuery

Events

An 'event' is when something happens. For example when the user mouses over a link in a web page.


element.onmouseover = function () {
  //code to execute when the mouse over happens
};
				

Types of Events

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

  • 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

Events Created via HTML

You can create a JavaScript event via HTML and call it via JavaScript.


<button id="clickMe" onclick="sayHi()">Click Me!</button>
				

function sayHi() {
    alert ('Hi!');
}
				

Events Created via HTML

A few things to know.

  1. It's much more common to set the events in your JavaScript file.
  2. You might still see this approach with older google analytics tracking.
  3. There are multiple ways to create events.

Basic Events Created via JavaScript

DOM Events work like many of the other things we have done.

1. Find the object


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

2. Then add an event to that object:


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

Let's Develop It

Download this sample code.

Create an alert box when you onmouseover the turtle image. Try another event of your choice.

Event Listeners

This is more of a modern way to work with Events by creating Event Listeners and Event Handlers.

Beware, this may not work in older browsers.

1. Find the object:


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

2. Add the Event Listener:


myTarget.addEventListener("click", clickHandler);
					

3. Add the Event Handler:


function clickHandler(){
alert ('Hi!');
}
					

Let's Develop It

Use the previously downloaded sample code.

Create an alert box when you onmouseover the turtle image using event listeners and event handlers. Try another event listener of your choice.

Sometimes Links Should Not Link

At times you might have an <a href="#">link</a> but you don't want to the href to go to another page.

There is a built-in method to handle that:


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

				

Note the event argument

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.

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 property.


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');
var button = document.getElementById('getValue');

button.addEventListener("click", handleClick);

function handleClick(event){
  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
          alert(radioButtonValue);
          break;
      }
  }
}
				

Submit buttons Maybe Shouldn't Submit?

If you are going to get form values by clicking the submit button we need to approach things in a different way.


var submitButton = document.getElementById('simpleSubmit');

simpleForm.addEventListener("submit", handleSubmit);

function handleSubmit(event){
  var resultsBox = document.getElementById('resultsBox');
  var inputValue = document.getElementById('inputValue');
  event.preventDefault();

  resultsBox.innerHTML = inputValue.value;

}
				

Let's Develop It

Collect a value from the input box on the page. Display that value on the page.

DOM Review

The browser automatically builds a Document object of the entire page.

To interact with the page you need to do at least 3 things

  1. Find the element and store it in a variable
  2. Create an Event Listener
  3. Create an Event Handler

Ways to find elements

  • By Id
  • By Tag Name
  • By Class Name

DOM Access: By Id

You can find nodes by id using the method:


document.getElementById(id);
	

To find:


<img id="bearPic" src="http://placebear.com/200/300" alt="bear"/>
	

We would use:


var imgBear = document.getElementById('bearPic');
console.log(imgBear);
	

DOM Access: By Tag Name

You can find list of elements by Tage Name:


document.getElementsByTagName(tagName);
	

To find:


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

We would use:


var listItems = document.getElementsByTagName('li');
console.log(listItems);
	

DOM Access: By Class Name

You can find a list of elements by class Name:


document.getElementsByClassName(className);
	

To find:


<h2 class="master-headline">My Blog Post</h2>
	

We would use:


var headline = document.getElementsByClassName('master-headline');
console.log(headline);
	

What Now? It's Time for Change

Now that the element is stored in a variable, we can access the properties and change them.

DOM Nodes: Attributes

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

To change this element:


<img id="bearPic" src="http://placebear.com/200/300" alt="bear"/>
	

We could change the src attribute this way:


var imgBear = document.getElementById('bearPic');
var oldSrc = imgBear.src;
imgBear.src = 'http://placebear.com/100/500';
	

DOM Nodes: Getting and Setting Attributes

You can also use getAttribute/setAttribute


<img id="bearPic" src="http://placebear.com/200/300" alt="bear"/>
	

We could change the src attribute this way:


var imgBear = document.getElementById('bearPic');
var oldSrc = imgBear.getAttribute('src');
imgBear.setAttribute('src', 'http://placebear.com/100/500');
	

DOM Nodes: Styles

The most common properties to change are styles.

To make this style change via JavaScript:


body {
color: red;
}
	

Use this JavaScript:


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

DOM Nodes: JavaScript Style Naming Conventions

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

To make this style change via JavaScript:


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

Use the previously downloaded sample code.

Isolate a node (an element on the page) and change an attribute or add a new style. Also try a style chnage via a button click.

Changing Text: 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!';
	

Let's Develop It

Use the previously downloaded sample code.

Lets spend some time changing and adding text on the screen using innerHTML.

Brand New HTML via JavaScript: 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://placebear.com/400/300';
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

Use the previously downloaded sample code.

Lets spend some time creating brand new HTML using createElement.

JQuery

jQuery is a fast, small, and feature-rich JavaScript library.

JQuery: DOM SELECTIOn

  • By Id
  • By Tag Name
  • By Class Name

DOM Access: By Id

You can find nodes by id using the method:


// VANILLA
document.getElementById(id);

// JQUERY
$(id);
	

To find:


<img id="bearPic" src="http://placebear.com/200/300" alt="bear"/>
	

We would use:


// VANILLA
var imgBear = document.getElementById('bearPic');

// JQUERY
var imgBear_jquery = $('bearPic');

	

DOM Access: By Tag Name

You can find list of elements by Tage Name:


// VANILLA
document.getElementsByTagName(tagName);

// JQUERY
$(tagName);
	

To find:


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

We would use:


// VANILLA
var listItems = document.getElementsByTagName('li');

// JQUERY
var listItems_jquery = $('li');
	

DOM Access: By Class Name

You can find a list of elements by class Name:


// VANILLA
document.getElementsByClassName(className);

// JQUERY
$(className);
	

To find:


<h2 class="master-headline">My Blog Post</h2>
	

We would use:


// VANILLA
var headline = document.getElementsByClassName('master-headline');

// JQUERY
$('master-headline');
	

CSS Changes are a Breeze:


$( "div" ).css( "border", "9px solid red" );
	

jQuery

It's handy, has a consistent syntax, and is known for cross browser implementation.

Summary

  • Events
  • Listeners
  • Forms
  • DOM
  • DOM Methods
  • DOM Node Styles
  • Intro to JQuery

What Now?

Now it's time for you to go out a build something! You now have the knowledge to:

  • Create interactive Web Pages
  • Lend a helping hand and debug code at work or on a side project
  • Build what YOU want to build

Resources

Thank You