Web Programming & Interactivity with JavaScript
A 2-hour introduction for researchers building interactive web content
Overview
This workshop introduces JavaScript as the programming layer of the web, starting from lesson_1.zip You should already have basic familiarity with HTML and CSS prior to proceeding.
- Duration: 2 hours
- Prerequisites: Basic HTML & CSS
- Outcome: Added interactivity to webpage
Setup
You may use the same environment as the HTML/CSS workshop. Please create a js>index.js file so you have all the files below in your website folder.
index.htmlstyle>style.cssjs>index.jsTo load this index.js file within your webpage add the following line to the <head> element of your HTML file:
<script src="js/index.js"></script>
The Role of JavaScript
JavaScript enables behavior and interactivity on the web.
- Responding to user actions
- Showing or hiding content
- Updating pages without reloading
- Supporting interactive figures, maps, and tools
- Interactive data visualizations
- Search and filtering interfaces
- Demonstration tools and calculators
JavaScript Basics
JavaScript is a programming language that runs in the browser.
Variables
Declare variables using let, const (for contants), or (older) var.
// A simple variable
let projectTitle = "Weather Data Explorer";
// Logging output
console.log(projectTitle);
To see console.log information: In Chrome - click View>Developer>Developer Tools, then select Console.
Variable names must:
- Start with a letter, _, or $
- Contain only letters, numbers, _, or $
- Not start with a number
- Not be a reserved keyword
JavaScript is case-sensitive. So variables named 'age' and 'Age' are different. Best to keep variables in consistent case (e.g., camelCase).
Variable Types
String
let name = "Kevin";
let greeting = 'Hello';
let message = `Hi ${name}`; // template string
Number
let age = 42;
let price = 19.99;
let infinity = Infinity;
let notANumber = NaN;
Boolean
let isLoggedIn = true;
let isAdmin = false;
Object
Key–value pairs.
const user = {
name: "Kevin",
role: "Researcher"
};
//to get the 'name' key (two ways)
console.log(user.name, user['name'])
Array
Ordered lists (arrays are objects).
const numbers = [1, 2, 3, 4];
//to get the first value in the array
console.log(numbers[0])
Date
For working with dates and times.
const today = new Date();
Undefined and Null
let result;
console.log(result); // undefined
let selectedItem = null;
Functions, Conditionals and Loops
Functions
// A basic function
function greetUser(name) {
return "Welcome, " + name;
}
// As an arrow function
// structure: const functionName = (parameters) => { function body };
const greetUser = (name) => {
return "Welcome, " + name;
};
// since it’s a one-liner, the extra braces and return are optional
const greetUser = name => "Welcome, " + name;
Conditionals
if
const temperature = 85;
if (temperature > 80) {
console.log("It's hot outside");
}
if / else
const isLoggedIn = false;
if (isLoggedIn) {
console.log("Welcome back!");
} else {
console.log("Please log in");
}
if / else if / else
const score = 72;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else {
console.log("Grade: F");
}
Comparison operators in conditionals
5 === 5 // true (strict equality)
5 == "5" // true (type coercion – usually avoid)
5 !== 3 // true
10 > 3 // true
5 <= 5 // true
Logical operators (&&, ||, !)
const isAdmin = true;
const isLoggedIn = true;
if (isAdmin && isLoggedIn) {
console.log("Access granted");
}
///
const hasTicket = false;
const isVIP = true;
if (hasTicket || isVIP) {
console.log("You may enter");
}
Switch Statement
Good when comparing one value against many options.
const day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the week");
break;
case "Friday":
console.log("Almost weekend");
break;
case "Saturday":
case "Sunday":
console.log("Weekend!");
break;
default:
console.log("Midweek day");
}
Loops
for loop (classic)
for (let i = 0; i < 5; i++) {
console.log(i);
}
Looping through an array with for
const colors = ["red", "green", "blue"];
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
for...of (modern & clean)
Best for looping over values in arrays and strings.const fruits = ["apple", "banana", "orange"];
for (const fruit of fruits) {
console.log(fruit);
}
for...in (objects)
const user = {
name: "Kevin",
role: "Researcher"
};
for (const key in user) {
console.log(key, user[key]);
}
while loop
Runs while a condition is true.let count = 0;
while (count < 3) {
console.log(count);
count++;
}
do...while
Runs at least once, even if the condition is false.let num = 5;
do {
console.log(num);
num++;
} while (num < 3);
break and continue
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // skip 3
}
if (i === 5) {
break; // stop loop
}
console.log(i);
}
Array methods (loops you’ll actually use a lot)
Array methods (loops you’ll actually use a lot)
const numbers = [1, 2, 3];
numbers.forEach(num => {
console.log(num * 2);
});
map
Creates a new array.
const tempsC = [0, 10, 20];
const tempsF = tempsC.map(c => (c * 9/5) + 32);
filter
Keeps items that match a condition.
const scores = [55, 78, 92, 60];
const passing = scores.filter(score => score >= 70);
reduce
Accumulates values into one result.
const data = [10, 20, 30];
const total = data.reduce((sum, value) => sum + value, 0);
Mini Exercise (5–7 min)
From within your index.js file, write and test a function called 'fToC' that converts fahrenheit to celsius
//Step 1: create fahrenheit to celsius function noting celsius = (fahrenheit - 32) * 5 / 9
// Step 2: test the function with different values to make sure it works as expected
When you're done, save the file and test it in your web browser.
The DOM: Connecting JavaScript to HTML
The Document Object Model (DOM) allows JavaScript to read and change HTML.
To make sure the HTML elements are present before the JavaScript runs, be sure to wait for the 'DOMContentLoaded' event to fire, see below
document.addEventListener('DOMContentLoaded', () => {
// Select an element
const heading = document.querySelector("h1");
console.log(heading)
// Change its text
heading.textContent = projectTitle;
});
Think of the DOM as a bridge between your HTML structure and JavaScript logic.
Events & User Interaction
Events allow your page to respond to user actions such as clicks or typing.> The following example shows how to show/hide an element:
HTML
<button class="tab-button active" data-tab="forcast_table">
Table
</button>
<div id="forcast_table" class="tab-panel active">
Forcast Table
<div>
JavaScript
const button = document.querySelector(".tab-button");
const forcast_table = document.querySelector("#forcast_table");
button.addEventListener("click", () => {
forcast_table.hidden = !forcast_table.hidden;
});
Mini Exercise (5–7 min)
Create a button to call your fahrenheit to celsius conversion function
- Create button in HTML
- Wait for DOMContentLoaded event
- Add interactivity to button click event
Looping through DOM elements
It may be beneficial to loop through all the elements on your webpage. This allows you to add intereactivity to multiple elements without having to write code for each one. Here's how you can accomplish this:
const buttons = document.querySelectorAll('.tab-button');
buttons.forEach(button => {
button.addEventListener("click", () => {
console.log("Button clicked");
});
});
More information on querySelectorAll
Tabs
Often times the web interface isn't large enough to show all the content at once. A common solution is to use tabs to show and hide different sections of content. The following example shows how to show/hide different content sections using JavaScript and CSS.
HTML
<div class="tabs">
<button class="tab-button active" data-tab="forcast_table">
Table
</button>
<button class="tab-button" data-tab="forcast_chart">
Chart
</button>
</div>
<div class="tab-content">
<div id="forcast_table" class="tab-panel active">
Forcast Table
</div>
<div id="forcast_chart" class="tab-panel">
Forcast Chart
</div>
</div>
CSS
JavaScript
const buttons = document.querySelectorAll('.tab-button');
const panels = document.querySelectorAll('.tab-panel');
buttons.forEach(button => {
button.addEventListener('click', () => {
const target = button.dataset.tab;
// Update button states
buttons.forEach(b => b.classList.remove('active'));
button.classList.add('active');
// Update panel visibility
panels.forEach(panel => {
panel.classList.toggle(
'active',
panel.id === target
);
});
});
});
The complete code for this example can been seen at lesson 2, and can be download from lesson_2.zip.