how to think in code
I need to remember something so I can use it later
Use a variable.
var a = "To be or not to be"
var b = 100
var c = false
I need to make a decision between two or more options
Use an if/else conditional statement
if (x < 100) {
// do something
} else {
// do something else
}
or
if (name=="Ben") {
// do something
} else {
// do something else
}
I need to change what my website looks like
Use the style property
HTML:
<div id="title"></div>
JavaScript:
var t = document.getElementById("title")
t.style.color = "#00aaff"
t.style.border = "solid 2px #0af"
t.style.backgroundColor = "#eeeeee"
I need to save an action so I can do it later
Use a function
function changeBG() {
//do something
}
// later, you can invoke it
changeBG()
I need my action to happen a little bit differently each time
Use a function with an argument
function changeBG(color) {
document.body.style.backgroundColor = color
}
// later, you can invoke it with different colors
changeBG("black")
changeBG("white")
I need to add something to my page
Use createElement and appendChild
var t = document.createElement("div")
t.innerHTML = "Lorem Ipsum"
var parenttobe = document.getElementById("title")
parenttobe.appendChild(t)
more advanced
I need to remember a lot of things that are related somehow
Use an array
var groceries = [ "milk", "eggs", "bread" ]
groceries[0] // returns "milk"
or use an object
var groceries = {
milk: "1 gallon",
eggs: "1 dozen",
bread: "1 loaf"
}
groceries.milk // returns "1 gallon"
I need to do something several times
Use a loop
for (var i=0;i<100;i++) {
//the code in here will happen 100 times
}
I need to make something on my site interactive
Use an event listener
HTML:
<div id="title"></div>
JavaScript:
var t = document.getElementById("title")
t.addEventListener("click", function(event) {
//do something in here
//a ton of info is provided in the 'event' argument
})
examples
Remember, there are a dozen ways to code any given idea. It is usually easier to understand your own code than to read someone else's. Steal the essentials and go be creative!