<script src="link"></script>
Embedding JS in HTML
<script src="/path/to/script.js"></script>
Linking JS in HTML
Declaring a variable
var name = "" // declaring it as a blank string
var name = 0 // declaring it as a number
var name = [] // declaring it as an array - arrays should always have similar data, different answers to the same question
var name = true //declaring it as boolean
useful for declaring global variables that will be used within functions,
or for declarinig variables that will get their values later in the code
used for notifying the user
alert("this is a statment")
used for asking the user a yes or no question, which can be saved as a bolean variable
confirm("is this true or false")
used for asking a question that the user will type out a string to answer such as their name, favorite xx or pets name
prompt("this is a question, the user will answer with a string")
used to display data in the console
console.log("Your total is " + varPrice) // will console log the string and the price stored in the variable
conditional statments execute different code depending on the truth value of the statment in the (parenthesis), and the code is found in the {curley brackets}
if (statment is true) {
execute this
} else if (this 2nd statement is true) {
execute this one
} else {
if all else fails do this
}
var truth = true
if (truth === true) {
alert("true")
} else if (truth === false) {
alert("false")
} else {
alert("variable is not boolean")
}
returns the length of a variable or array
var variable = [ "q", "w", "e", "r", "t", "y" ]
console.log(variable.length) // logs the length (in this case 6)
console.log(variable[2]) // logs the third item in an array (arrays start at [0])
console.log(variable[variable.length - 2]) // logs "t"
searches an array for a value
var list = ["bassnectar", "glitch mob", "marvel years", "grizmatik"] // creates an array
console.log(list.indexOf("bassnectar")) // returns 0
console.log(list.indexOf("grizmatik")) // returns 3
console.log(list.indexOf("govinda")) // returns -1 becaue it is not in the array
can be used to change strings to integers
(but has other uses well beyond the scope of this document see here)
var myAge = "5" // in this example we see parseInt change a value from a string to an integer
console.log(myAge + 2) // unexpected output
console.log(parseInt(myAge) + 2) // expected output
changes strings to all lower case
var names = [ "Eric", "Beth", "Tim", "Autumn", "Dom", "Maria" ]
console.log(names[0]) // logs "Eric"
console.log(names[5].toLowerCase()) // logs "maria"
for loops
var variable = [ "q", "w", "e", "r", "t", "y" ]
for (var i = 0; i < variable.length; i++) { //basic syntax
console.log(variable[i]) //lists every value in the array
}
for (var i = 0; i < 10; i++) { // Loops from 0 to 9.
console.log("My value is " + i); // Prints a message and the current i value to the console.
}
reads a character in a string
var myName = "Eric"
console.log(myName.charAt(0)) //logs "E"
console.log(myName.charAt(0).toLowerCase()) //logs "e"
if (myName.charAt(0) === "E") {
console.log("match")
} else {
console.log("not a match")
}
var variable = [ "Eric", "Beth", "Tim", "Autumn", "Dom", "Maria" ]
for (var i = 0; i < variable.length; i++) {
console.log(variable[i]) // logs each item in the array
if (variable[i].charAt(0) === "E") {
console.log("This item starts with an E")
}
}
= is used to set a variable
var = value
== is used to compare values, but is not "strict"
1 == "1" // returns true
=== compares values, "strict", meaning both type (string, numeric, boolean, etc..) and value are equal
1 === "1" // returns false because the first value is a number, and the second value is a string
4 === 4 // returns true
double ampersand = logical AND
var a = 1
var b = 2
console.log(a === 1 && b === 1) // returns false
double pipe = logical OR
var a = 1
var b = 2
console.log(a === 1 || b === 1) // returns true
logical NOT
var a = 1
var b = 2
console.log(b !== 1) // returns true
console.log(a !== b) // returns true
produces random numbers
var rando = Math.random() * 10 // produces a number between 1 and 10 (Math.random produces a number between 0 and 1, multiplying it by 10 gives us our range, for example if Math.random produces 0.41 and we multiply it by 10 we get 4.1
rounds down to the next integer
console.log(Math.floor(4.1)) // logs 4
console.log(Math.floor(Math.random() * 10 + 1) // produces a number between 1 and 10 ( if we don't add 1 the range becomes 0-9 since Math.floor() is always rounding down)
var validInput = [ "q", "w", "e", "r", "t", "y" ] // valid inputs
userInput = prompt("Enter Q W E R T or Y")
inputLC = userInput.toLowerCase()
if (userInput = inputLC) {
//continue running logic / nested logic
} else {
alert("Please try again")
}
}
You can create a variable of arrays, which each are their own array
var rockMus = [ "mushroomhead", "atreyu", "rage against the machine", "3teeth" ]
var edmMus = [ "bassnectar", "glitch mob", "marvel years", "grizmatik" ]
var rapMus = [ "biggie", "sts", "cudi", "immortal technique" ]
var music = [rockMus, edmMus, rapMus]
console.log(music[0][0]) // logs mushroomhead
console.log(music[0][2]) // logs ratm
console.log(music[1][0]) // logs bassnectar
console.log(music[2][3]) // logs immortal technique
//log all values in nested arrays
for ( i = 0; i < music.length; i++) {
for (j = 0; j < music[i].length; j++) {
console.log(music[i][j])
}
}
The best way to do anything in JavaScript. Functions can do anything
function newFunction(data) { // create our function
console.log(data)
}
newFunction(variable) // call our function and feed it our variable, it logs the value
--
function newFunct() {
console.log("you can use a function for anything")
console.log("feed it data in the parenthesis")
console.log("and everything within the {} will execute when you call it")
}
newFunct() //call our function
--
//create our arrays
var rockMus = [ "mushroomhead", "atreyu", "rage against the machine", "3teeth" ]
var edmMus = [ "bassnectar", "glitch mob", "marvel years", "grizmatik" ]
var rapMus = [ "biggie", "sts", "cudi", "immortal technique" ]
//write a function to log the data within any array we feed it
function complex(data) {
for (i = 0; i < data.length; i++) {
console.log(data[i])
}
}
//call our function, and feed it various arrays
complex(rockMus)
complex(edmMus)
complex(rapMus)
--
function add(x, y, z) {
return x + y + z
}
console.log(add(2, 3, 2))
var a = add(1, 2, 3)
console.log(a)
returns an answer and stops the function that called it
//create arrays
var rockMus = [ "atreyu" ]
var edmMus = [ "bassnectar", "glitch mob", "marvel years", "grizmatik" ]
var rapMus = [ "sts", "cudi", "immortal technique" ]
//create our function
function length(data) {
return(data.length)
}
//call our function
var x = length(rockMus)
var y = length(edmMus)
var z = length(rapMus)
//log the results
console.log(x)
console.log(y)
console.log(z)
returns the type of value of a variable (but has other uses well beyond the scope of this document see here)
var variable = 6
var edmMus = [ "bassnectar", "glitch mob", "marvel years", "grizmatik" ]
var name = "Eric"
var truth = false
console.log(typeof variable) //logs number
console.log(typeof edmMus) //logs object
console.log(typeof name) //logs string
console.log(typeof truth) //logs boolean
complex data type that can hold anything from variable, to arrays, other objects, functions etc..
The text version of this object can be found here for testing
refers to the object holding it
see "objects"
basic syntax
var array = [
{ q: "2+2", a: 4 },
{ q: "4+2", a: 6 },
{ q: "red is blue", a: false },
{ q: "i am groot", a: "huh?" }
]
console.log(array[0].q)
console.log(array[3].a)
The window object contains a plethora of information
console.log(window) // do this in dev tools
console.log(window.screen.width)
console.log(window.location.href)
The window object contains a plethora of information
console.log(window) // do this in dev tools
console.log(window.screen.width)
console.log(window.location.href)
Everything in an HTML document is a node
console.log(document.body) //html body console.log(document.body.children) //all children of body console.log(document.body.children[3]) //4th child console.log(document.body.children[3].childNodes[7].parentElement.style.color = "red"); //change the style of selected nodes
All nodes can be accessed by javascript
New nodes can be created, and all nodes can be modified or deleted
Nodes have a hierarchical relationship to each other.
the terms parent, child and sibling can also be used
You can use the following node properties to navigate between nodes with JavaScript:
parentNode
childNodes[nodenumber]
firstChild
lastChild
nextSibling
previousSibling
//these examples all retrieve the text from one element(head1) and copy it to second element(para)
document.getElementById("para").innerHTML = document.getElementById("head1").innerHTML;
document.getElementById("para").innerHTML = document.getElementById("head1").firstChild.nodeValue;
document.getElementById("para").innerHTML = document.getElementById("head1").childNodes[0].nodeValue;
document.getElementById("para").textContent = document.getElementById("head1").childNodes[0].textContent;
querySelector returns the first hit it finds, while querySelectorAll returns all matching nodes
var pTags = document.querySelectorAll("p") //returns all paragraph tags
var pTags = document.querySelector("p") //returns the first paragraph tag it finds
allows you to dynamically set an attribute, such as href to a tags, or scr to images
<h1 id="head1">this is a heading</h1>
<p id="para">...</p>
<p>para2</p>
<a>This is a link</a>
<img id="img1">
<img class="clas">
var aTags = document.querySelector("a")
aTags.setAttribute("href", "http://google.com")
var imgTags = document.querySelector("img")
imgTags.setAttribute("src", "https://www.w3schools.com/js/pic_htmltree.gif")
var imgTags = document.querySelectorAll("img")
imgTags[0].setAttribute("src", "https://www.w3schools.com/js/pic_htmltree.gif")
imgTags[1].setAttribute("src", "https://www.w3schools.com/js/pic_htmltree.gif")
var imgTag1 = document.querySelector("#img1")
imgTag1.setAttribute("src", "https://www.w3schools.com/js/pic_htmltree.gif")
var clas = document.querySelector(".clas")
clas.setAttribute("style", "border:1px solid black;")
allows you to insert html into a node
document.getElementById("para").innerHTML = "This text was created with JS" document.getElementById("para").innerHTML = "<h1>A dynamic heading appears</h1>"
similar to innerHTML but a better choice from a security standpoint
document.getElementById("para").textContent = "This text was created with JS"
Creates and appends new HTML to the bottom of an html doc
var tag = document.createElement("h1")
tag.textContent = "This H1 was made via prompts"
document.body.appendChild(tag)
var secondsLeft = 10;
function setTime() {
var timerInterval = setInterval(function() {
secondsLeft--;
//code to run or display while timer is running goes here
if(secondsLeft === 0) {
clearInterval(timerInterval);
//code to run or display when timer runs out goes here
}
}, 1000); //interval in ms
}
setTime();
turns a string into an array
.split(" ") //seperates at spaces
.split("") // seperates each letter
.split() // turns the entire string into the first value of an array
var test = "this isnt a test, is it?"
test3 = test.split(" i") //seperates the original values whenever it finds " i" (space i)
console.log(test3) // expected output [ 'this', 'snt a test,', 's', 't?' ]
most often used to capture clicks on a specific node in the DOM, and run a block of js in responce to the click.
.addEventListener can respond to any HTML DOM event,
see here, but the most common events can be
found here.
Basic Syntax
var node = document.querySelector("#id")
node.addEventListener("click", function() {
});
added to .addEventListener events to prevent the default behavior Often used to prevent forms from refreshing when they're submitted, or to prevent a link from being followed when the use clicks on it .preventDefault is a wildly powerful tool, that can prevent mouse clicks, keystrokes or checkboxes being checked when a user clicks on them it also cancels any subsequent actions that the default action would have triggered
submit.addEventListener("click", function(event) {
event.preventDefault();
var response = "Thank you for your submission " + name.value
Response.textContent = response;
});
changes css properties. hyphen notation is converted to camelcase
document.querySelector("#div").style.fontFamily = typeface;
executes a provided function for each array element
var arr = ["a", "b", "c", "d"]
arr.forEach(function(element) {
console.log(element)
})
// expected output: a
// expected output: b
// expected output: c
// expected output: d
splits strings into arrays at defined character
var char = "abcd".split("");
console.log(char)
// expected output [ 'a', 'b', 'c', 'd' ]
var char = "ab,cd"
console.log(char.split(","))
// expected output [ 'ab', 'cd' ]
x+=y is the same as x=x+y
assignment operators add a value to a variable
other operators work the same way (-=, *=, /=, %=, **=)
there are even more, but beyond the scope of this doc see here
var x = 2
var y = 3
x+=y
console.log(x)
// expected output 5
var x = 2
var y = 3
console.log(x = x+y)
console.log(x+=y)
// expected output 5
// expected output 5
// actual output 5
// actual output 8 // because we're mutating the data twice, even by simply logging it.
events bubble upward - if we have a button (with a click event) inside a div (with another click event) and we click the button, the div will recieve a click as well.
we can stop this with .stopPropagation()
run the following code and comment in and out the .stopPropagation() lines to see how it works
<!DOCTYPE html>
<head>
<style>div {margin: 30px;}</style>
</head>
<body>
<div class="outer-div"> Click me
<div class="inner-div"> Click me
<div>
<button class="button">Click me</button>
</div>
</div>
</div>
<script>
var outer = document.querySelector(".outer-div");
var inner = document.querySelector(".inner-div");
var button = document.querySelector(".button");
function btnClick(event) {
//event.stopPropagation();
alert("You clicked the button")
}
function innerClick(event) {
//event.stopPropagation();
alert("You clicked the inner div")
}
function outerClick(event) {
//event.stopPropagation();
alert("You clicked the outer div")
}
outer.addEventListener("click", outerClick);
inner.addEventListener("click", innerClick);
button.addEventListener("click", btnClick);
</script>
</body>
</html>
<body>
<div class="container">
<form>
<ul id="list">
<li id="0" >
opt0 <button>Add to Cart</button>
</li>
<li id="1">
opt1 <button>Add to Cart</button>
</li>
<li id="2">
opt2 <button>Add to Cart</button>
</li>
<li id="3">
opt3 <button>Add to Cart</button>
</li>
<li id="4">
opt4 <button>Add to Cart</button>
</li>
</ul>
</form>
<div id="selected">
</div>
</div>
<script>
var list = document.querySelector("#list"); // for the click listener
var selected = document.querySelector("#selected"); // to append new divs
var arr = ["option0", "option1", "option2", "option3", "option4"];
list.addEventListener("click", function(event) { // we create a listener on the ul node
event.preventDefault();
if(event.target.matches("button")) { // the button creates the event we're looking for
var item = document.createElement("div");
item.textContent = arr[event.target.parentElement.id]; // key here is parent element.id
selected.append(item);
}
})
</script>
</body>
store variables in local storage for retrival later
//setting a variable
var variable = ""
localStorage.setItem("variable", variable) // ("var name", var value)
// retrieving a variable
var variable = localStorage.getItem("variable")
eliminates leading spaces and trailing spaces
var name = " eric "
console.log(name.trim())
//expected output "eric"
to store objects in local storage we have to stringify them on the way in and parse when we retrieve them
// Put the object into storage
localStorage.setItem("testObject", JSON.stringify(testObject))
// Retrieve the object from storage
var retrievedObject = localStorage.getItem("testObject")
console.log(JSON.parse(retrievedObject))
returns the element that triggered the event, not always the eventListeners element
sets and retrieves attributes from a node
var imageContainer = document.querySelector(".img-container")
imageContainer.addEventListener("click", function(event) {
var element = event.target;
if (element.matches("img")) {
var state = element.getAttribute("data-state");
if (state === "still") {
element.setAttribute("data-state", "animate");
element.setAttribute("src", element.getAttribute("data-animate"));
} else if (state === "animate") {
element.setAttribute("data-state", "still");
element.setAttribute("src", element.getAttribute("data-still"));
}
}
})