Web 102 Cheat Sheet
Refer to these examples to jump-start development in HTML and basic JavaScript.
HTML
Link a JavaScript file
<script src="script.js"></script>
Create a button that calls a function
<button onclick="myFunction()">My Function</button>
Create a text input
<input type="text" id="my-input" />
Create an image
<img src="http://example.com/urlToImage.png" />
JavaScript
Define a function
function myFunction(parameter1, parameter2...) {
}
Call a function
myFunction(argument1, argument2...);
Create a variable
let x = "new variable";
Set a variable
x = 5;
Increment the value of a variable by 1
x++;
Increment the value of a variable by any number (like 10)
// replace 10 with the desired number
x += 10;
Find the maximum of some variables
let count1 = 5;
let count2 = 9;
let count3 = 4;
let maximumCount = Math.max(count1, count2, count3);
Generate a random number between 1 and any number
let random = Math.ceil(Math.random()*10);
Display a message to the user
alert("This is a message");
Make a string with embedded expressions and linebreaks
let adjective = "good";
let noun = "statement";
let myMessage = `this is
a very ${adjective} message.
and it is a ${noun}.`;
alert(myMessage);
Will print:
this is
a very good message.
and it is a statement.
Ask a question to the user
let answer = prompt("This is a question");
Do something if a condition is true
let answer = "question";
if (answer === "Answer") {
alert("Do something");
}
Will print nothing; condition is not met.
Do something if a condition is false
let answer = "Answer2";
if (answer === "Answer1") {
alert("Do something");
} else if (answer === "Answer2") {
alert("Do something else if");
} else {
alert("Do something else");
}
Will print:
Do something else if
Get the value from an HTML text input
HTML
<input id="my-input" />
JavaScript
let textInput = document.querySelector("#my-input");
let textValue = textInput.value;
Create a new HTML element
let newParagraph = document.createElement("p");
Insert an HTML element into the body
of the page
document.body.appendChild(newParagraph);
Insert an HTML element into another element
let myDiv = document.querySelector("#my-div");
myDiv.appendChild(newParagraph);
Set the text content of an HTML element
myParagraph.textContent = "New Text Content";
Set a CSS property of an HTML element
myParagraph.style.color = "red";
Change the background color of the whole page
document.body.style.background = "red";
Repeat code a certain number of times
// replace 10 with the desired number
for (let i = 0; i < 10; i++) {
alert("Repeat");
}