Interactivity with JavaScript

This is a gallery of lessons from Khan Academy's HTML/JS Making Webpages Interactive course.

0%
the DOM or Document Object Model

JS and the DOM

Learn how to control the DOM or Document Object Model with JavaScript.

the DOM or Document Object Model

DOM access methods

Learn the DOM API in JavaScript to access your webpages.s

the DOM or Document Object Model

DOM modification

Learn to use JavaScript to modify styles and attributes, and create new elements.

the DOM or Document Object Model

DOM events

Use the DOM API to make your page react to events like clicks, scrolls, and data entered in fields.

the DOM or Document Object Model

DOM animation

Animate parts of your webpage using window.setInterval, window.requestAnimationFrame, and CSS animations and transitions.

the DOM or Document Object Model

JS libraries

Include JS libraries in your page to harness the power of the open source community.

Internal Scripts

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript">
      var helloFunction = function(){
        alert("Hello world");
      }
    </script>
  </head>
  <body>
    <button onclick="helloFunction()">Push Me!</button>
    <button onclick="goodbyeFunction()">Don't Push Me!</button>
    <script type="text/javascript">
      var goodbyeFunction = function(){
        alert("Goodbye world");
      }
    </script>
  </body>
</html>

External Scripts

<!DOCTYPE html>
<html>
  <head>
    <script src="app.js"> </script>
  </head>
  <body>
  </body>
</html>
/** app.js **/
var message = "Hello world!";
console.log(message);

External Scripts

<!DOCTYPE html>
<html>
  <head>
    <script src="app.js"> </script>
  </head>
  <body>
  </body>
</html>
/** app.js **/
/**** This writes the message to the page ****/ document.body.innerHTML = "Hello again!";

Lesson 1 Quiz

What does DOM stand for?

Data Overlay Mode

Document Object Model

Div Oriented Manipulation

Disk-on-a-model

What is the correct way to add an external script?

<script src="app.js"/>

<script href="app.js"></script>

<script src="app.js"></script>

<script href="app.js"/>

Which code snippet is correct?

document.innerHTML = "Hello world!";

document.body.innerHTML("Hello world!");

document.innerHTML("Hello world!");

document.body.innerHTML = "Hello world!";

JS and the DOM

Putting JS in a webpage

You can apply JavaScript in the inline, internally in the head or body tags, or in external script files.

Simple Javascript Methods

console.log("Message" + variable)

This is a great testing tool to check to see if your JavaScript is doing what you want it to be doing.

You can press COMMAND + OPTION on a Mac or CONTROL + SHIFT on a Windows machine to view the console.

alert("Message" + variable);

Not a good final product for an app or website, this is also more of a testing tool for the developer.

This is a dialog box that pops up with a OK.

confirm("Message" + variable);

This is a dialog box that pops up with both OK and CANCEL buttons.

prompt("Message" + variable);

Another relic of the 1990's, this is a dialog box that pops up allowing for user input.

DOM manipulation

We can access the DOM or Document Object Model with the document keyword.

 

Example Code:

document methods

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <h1 id="heading">Original Heading</h1>
    <section class="content">
      <p>Paragraph One</p>
      <p>Paragraph Two</p>
    </section>
    <section class="content">
      <p>Paragraph Three</p>
      <p>Paragraph Four</p>
    </section>
    <script type="text/javascript" src="app.js"></script>
  </body>
</html>
/* app.js */
var heading = document.getElementById('heading'); /* returns one node or element */
var content = document.getElementsByClass('content'); /* returns an array */
var paragraphs = document.getElementsByTagName('p'); /* returns an array */
heading.innerHTML = "Page Title"; p.style('background', 'yellow'); for (var i = 0; i < content.length; i++) { content[i].innerHTML = "Content populated via for loop"; }

Accessing by CSS Selector

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="styles.css"> </script>
  </head>
  <body>
    <section>
      <h1 id="topHeading">Heading</h1>
      <p class="paragraph">Paragraph One</p>
      <p class="paragraph">Paragraph Two</p>
      <p class="paragraph">Paragraph Three</p>
      <p class="paragraph">Paragraph Four</p>
    </section>
    <script src="app.js"></script>
  </body>
</html>
/* styles.css */
#topHeading {
  text-shadow: 1px 1px 1px lightgray;
}
section .paragraph {
  font-family: Fantasy;
}
/** app.js **/
var topHeading = document.querySelector('#topHeading'); var paragraphs = document.querySelectorAll('section .paragraph');
var totalParagraphs = paragraphs.length; confirm("There are " + totalParagraphs + " on the page.");

Advanced CSS Selectors

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="styles.css"> </script>
  </head>
  <body>
    <section id="topSection">
      <h1 id="topHeading onmouseover="changeBack();">Heading</h1>
      <p class="paragraph">Paragraph One</p>
      <p class="paragraph">Paragraph Two</p>
      <p class="paragraph">Paragraph Three</p>
      <p class="paragraph">Paragraph Four</p>
      <p class="paragraph">Paragraph Five</p>
      <p class="paragraph">Paragraph Sixe</p>
      <p class="paragraph">Paragraph Seven</p>
      <p class="paragraph">Paragraph Eight</p>
    </section>
    <script src="app.js"></script>
  </body>
</html>
/* styles.css */
#topSection .paragraph:first-child {
  font-weight: bold;
}
#topSection .paragraph:last-child {
  font-weight: light;
}
#topSection .paragraph:nth-child(3) {
  color: steelblue;
}
#topSection .paragraph:nth-child(3n + 2) {
  text-decoration: underline;
}
#topSection .paragraph:nth-child(even) {
  background-image: url('file://PATH-TO/img/darkblue_background.png');
}
#topSection .paragraph:nth-child(odd) {
  font-family: sans-serif;
}
/** app.js **/
var firstParagraph = document.querySelectorAll('#topSection .paragraph:first-child');

var lastParagraph = document.querySelectorAll('#topSection .paragraph:last-child');

var thirdParagraph = document.querySelectorAll('#topSection .paragraph:nth-child(3)');

var everyThirdStartingFromSecond = document.querySelectorAll('#topSection .paragraph:nth-child(3n + 2)');

var evenParagraphs = document.querySelectorAll('#topSection .paragraph:nth-child(even)');

var oddParagraphs = document.querySelectorAll('#topSection .paragraph:nth-child(odd)');

var changeBack = function(){
  firstParagraph.style.font-weight = "initial";
  lastParagraph.style.font-weight = "initial";
  thirdParagraph.style.color = "initial";
  everyThirdStartingFromSecond.style.text-decoration = "initial";
  evenParagraphs.style.background-image = "none";
  oddParagraphs.style.font-family = "initial";
}

Lesson 2 Quiz

Which selection is INCORRECT?

document.getElementById('id_name');

document.getElementsByClass('class_name');

document.getElementsByType('html_tag');

document.querySelectorsAll('parent #id_name, parent .class_name');

You will need to use a for loop to access html values in ALL EXCEPT:

document.querySelector('#id_name')

document.getElementsByClass('class_name');

document.querySelectorAll('.team-member')

document.getElementsByTagName('tag_name'))

Using the :nth-child pseudo-selector, what does the 2 mean in p:nth(3n + 2) mean?

Starting from the 2nd item, every next 3rd item.

Starting from the 3rd item, every next 2nd item.

Items that are multiples of 5.

The 5th item.

DOM access methods

We can continue using the document keyword to access DOM nodes.

  • document.getElementById('id_name');
  • document.getElementsByClass('class_name');
  • document.getElementsByType('html_tag');

Accessing by CSS Selector

The document keyword can also access by CSS selectors and pseudo-selectors.

  • document.querySelector('#id_name');
  • document.querySelectorAll('parent #id_name, parent .class_name');
  • document.querySelectorAll('#parent_id .class_name:first-child');
  • document.querySelectorAll('#parent_id .class_name:last-child');
  • document.querySelectorAll('#parent_id .class_name:nth-child(3)');
  • document.querySelectorAll('#parent_id .class_name:nth-child(3n + 2)');
  • document.querySelectorAll('#parent_id .class_name:nth-child(even)');
  • document.querySelectorAll('#parent_id .class_name:nth-child(odd)');

 

Example Code:

Attribute Selectors

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <h1 id="galleryHeading"></h1>
    <img class="images"/>
    <img class="images"/>
    <img class="images"/>
    <button></button>
    <script type="text/javascript" src="app.js"></script>
  </body>
</html>
/** app.js **/
/*** assume that in the img folder, we have the following images:
  background01.png
  background02.png
  background03.png
***/
var galleryHeading = document.getElementById('galleryHeading');
galleryHeading.textContent = 'Image Gallery';
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++){
  images[i].src = "img/background0" + (i + 1) + ".png";
}
var closeButton = document.getElementById('closeButton');
closeButton.innerHTML = '<strong>Close</strong>';
}

Using .style

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <video></video>
    <input type="file" accept="video/*"/>
    <script src="app.js"> </script>
  </body>
</html>
/** app.js **/
var video = document.querySelector('video');
video.src = "https://www.youtube.com/embed/iR01DKCgaH8";
video.allowFullScreen = true;
video.style.width = '100%';
var input = document.querySelector('input');
input.disabled = true;
/* notice below we must convert hyphenated words to camelCase */
input.style.boxShadow = '1px 1px 4px 1px #3d1';
input.style.backgroundColor = 'fuchsia';

Tweaking Classes

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <div class="container">
      <p class="content">This is the content.</p>
    </div>
    <script src="app.js"> </script>
  </body>
</html>
.changedDiv {
  height: 100%;
  width: 80%;
  background: #8f3f31;
  color: #13f3f8;
  display: -webkit-flex;
  box-shadow: 1px 1px 4px 1px #13f3f8;
}
.fancyFonts {
  font-family: Fantasy, Cursive;
  font-size: 1.5rem;
}
/** app.js **/
/* .container.className = 'changeDiv'; is a bug because it replaces the old class name */
.container.className += 'changeDiv';
.container.classList.add('fancyFonts');

Creating HTML Elements

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <div class="container">
    </div>
    <script src="app.js"></script>
  </body>
</html>
/** app.js **/
/*** creates image with necessary attributes ***/
var createImg = document.createElement('img');
createImg.src = "img/background.jpg";
createImg.alt = "Cyber blue background";
var divContainer = document.getElementsByClass('container');
var createText = document.createTextNode('This is the image caption.');
/*** creates text ***/
var createParagraph = document.createElement('p');
createParagraph.appendChild(createText);
createImg.appendChild(createParagraph);
/*** appends text to image ***/ for (){
  divContainer.appendChild(createImg);
}

Lesson 3 Quiz

What is a valid value to modify element.disabled?

1

true

""

"true"

What is the correct way to change the style of an element?

element.style = 'color: blue';

element.style.color = 'blue';

element.style('color: blue');

element.style('color') = 'blue';

Which code snippet is INCORRECT?

headingEl.style.backgroundColor = "salmon";

mainEl.className += " warning";

document.body.appendChild = imgEl;

mainEl.classList().add("warning");

DOM modification

When access a DOM element directly or via a for loop, we can use . or "dot" notation to access that attribute.

Other Attribute Selectors Include:
  • element.innerHTML
  • element.textContent
  • element.setAttribute('property', 'value');
  • anchorTag[i].href
  • img[i].alt
  • input.autosave
  • input.checked
  • element.class
  • element.datetime
  • button.disabled
  • button.enabled
  • element.id
  • input.required
  • element.target
  • element.value

You can see more at the following link.

Modifying Styles

We can similarly change styles by using .style.property = "value"; approach.

Adding Classes

Instead of littering your JavaScript with essential CSS rules, it's better to throw those CSS rules in a class and then use JavaScript to add and remove those classes.

  • .className = "newClass" sets or replaces one class name
  • .className += "newClass" adds another class
  • .classList.add('newClass') works in newer browsers

Check usability for your browser at the Can I Use website

Creating HTML Elements

You set elements to the .innerHTML, but here is another way:

  • var createElement = document.createElement('html_tag');
  • createElement.src = "img/source"
  • createElement.alt = "Image description"
  • document.body.appendChild(createElement);
  • var createText = document.createTextNode('Node text');
  • createElement.appendChild(createText);

However this was much more code than just using .innerHTML. It is more preferred to use libraries like jQuery for easier DOM modification.

 

Example Code:

Event Listeners

See the Pen Khan Demo - Button Event Listener by Craig Curtis (@craigocurtis) on CodePen.

DOM Event Types

See the Pen epGNGY by Craig Curtis (@craigocurtis) on CodePen.

Processing Forms

See the Pen Processing Forms - Khan Demo by Craig Curtis (@craigocurtis) on CodePen.

Preventing Event Defaults

See the Pen Random Light Chain - Preventing Anchor Link Defaults - Khan Demo by Craig Curtis (@craigocurtis) on CodePen.

Lesson 4 Quiz

Which event listener combination is false?

touch : blur

mouse : contextmenu

form : change

window : scroll

What is the correct way to access the mouse coordinates?

function(event){event.clientX;event.clientY;event.offsetX;event.offsetY}

function(event){event.offsetX;event.offsetY}

function(event){event.X;event.Y}

function(event){event.clientX;event.clientY}

Which form event is called when you leave an input?

focus

change

submit

blur

DOM events

We need to now use these JavaScript methods as scripts that responses to user interactions. These are called callback functions.

Event Listeners

One of the most common Event Listeners is the click function.

Passing in a named function

var element = document.getElementById('...');
var clickFunction = function(){...}
element.addEventListener('click', clickFunction);

Passing in an anonymous function

var element = document.getElementById('...');
element.addEventListener('click', function(){...});

Other Common Event Listeners include:
Mouse Events
  • click
  • dblclick
  • mousedown
  • mouseup
  • mouseenter
  • mouseleave
  • mousemove
  • mouseover
  • mousewheel
  • contextmenu
Key Events
  • keydown
  • keyup
  • keypress
Touch Events
  • touchstart
  • touchmove
  • touchend
  • touchcancel
Form Events
  • focus
  • blur
  • change
  • submit
Window Events
  • error
  • resize
  • scroll
  • hashchange
  • load
  • unload

DOM Event Types

THe browser records many event properties like the x and y positions of the mouse. We can use the mouseover event, for instance, to create a simple drawing app. We can pass in event as a parameter to access these properties.

var canvas = document.getElementById('canvas');
var onMouseMove = function(event){
  var paintBrush = document.createElement('div');
  paintBrush.className = 'paintBrush';
  document.body.appendChild('paintBrush');
  paintBrush.style.top = event.clientY + 'px';
  paintBrush.style.left = event.clientX + 'px';
}
canvas.addEventListener('mousemove', onMouseMove);

Processing Forms

Both styling and processing forms take a bit more skill. Forms especially are more difficult due to them requiring back-end languages like PHP, Ruby, Python, or some more modern back-end JavaScript like nodeJS. Here, we'll just be covering the front-end basics.

Key to forms is access user input. Therefore, target input field and then we can access the .value property. Regarding event listeners, we can check different inputs for events like focus, blur, change, and submit.

Preventing Event Defaults

You may want to prevent certain default actions in the broswer like page refresh. In order to stop this from happening, pass a parameter, preferably event to the function where the action is to be prevented. Then we can access the .preventDefault() method of that parameter.

function(event){event.preventDefault(); ... }

 

Example Code:

Coming Soon!

Coming Soon!

Coming Soon!

Lesson 5 Quiz

Coming Soon!

Coming Soon!

Coming Soon!

Coming Soon!

Coming Soon!

Coming Soon!

Coming Soon!

Coming Soon!

Coming Soon!

Coming Soon!

Coming Soon!

Coming Soon!

Coming Soon!

Coming Soon!

Coming Soon!

DOM animation

The window Object

 

Example Code:

Coming Soon!

Coming Soon!

Coming Soon!

Lesson 6 Quiz

Coming Soon!

Coming Soon!

Coming Soon!

Coming Soon!

Coming Soon!

Coming Soon!

Coming Soon!

Coming Soon!

Coming Soon!

Coming Soon!

Coming Soon!

Coming Soon!

Coming Soon!

Coming Soon!

Coming Soon!

Using JS libraries in your webpage

Learn how to include JS libraries on your webpage, so that you can use functionality built by other web developers.

 

Example Code: