The script tag allows us to add JavaScript code into an html file.
<!DOCTYPE html>
<html>
<head>
<title>Your Page Title</title>
</head>
<body>
<script>
// Script tags should go at the end of the body:
</script>
</body>
</html>
Allow us to add buttons to a web page:
<button>Click Me!</button>
We can add events to buttons using onclick. onclick is set to a function, which will execute when the button is clicked:
<button onclick=myFunction()>Click Me!</button>
Position determines whether an element is able to move from its current location.
// sets position relative to its initial position
div
{
position: relative;
}
// sets position relative to its closest positioned ancestor
div
{
position: absolute;
}
The styles left, right, top, and bottom can be used to reorient an element once their position has been changed. left moves an object from the left side of the container, right moves an object from the right side, top moves an object from the top, and bottom moves an object from the bottom.
Forms can be written using the <form></form> tag.
Forms are filled with <input> tags, which allow users to input data.
Forms make use of the attribute onsubmit, which executes a function when the form has been submitted. For example, <form onsubmit="myFunction()"></form> will execute the function myFunction when the form has been submitted. Forms normally submit data to a server, but to prevent that, use .preventDefault(). This will stop the form from submitting the data, and allow the webpage to remain static.
<input> tag has several attributes:
type - this determines the type of input expected of the user.
name - this gives the input a name. This is valuable when using serializeArray, as the name of the input is directly associated with the >value of the input.value - if an input does not take a value, then it's important to set a value so the input is associated with a specific value when using serializeArray. For example, <input type="radio" value="true"> will associate the value true with that radio input.Prints values to the console. Accessed by going to the browsers development tool.
var x = 5; console.log(x); // Output is 5
prompt() is a function that allows users to enter input.
var name = prompt("What is your name?");
console.log(name); // will print the value the user input from the prompt.
alert() provides a pop-up to users.
alert("This will show up at the top of the browser as a pop-up");
The Document Object Model (DOM) makes HTML elements mutable using other programming languages.
Here are some useful functions to access HTML elements:
// Select an element by id tag
document.getElementById("name-of-id");
// Can be set to variable
var el = document.getElementById("name-of-id");
// Select element by Tag
// creates a list of all the elements with that tag
var list = document.getElementsByTagName("p");
// Access elements from a list
// Access the 2nd index of a list
var individualElement = list[2];
// Access the children of an element
body.firstElementChild; // returns the first child element of body
body.lastElementChild; // returns the last child element of body
// Access a list of children
body.children; // returns a list of children
// Access parent of an element
el.parentElement; // returns the parent element of el
Create new elements:
// creates new h2 tag
document.createElement("h2");
// set to variable
var newTag = document.createElement("h2");
Add elements to HTML file:
// adds element newTag to the body
body.appendChild(newTag);
// adds new element before the existing element name-of-id to the body
body.insertBefore(newTag, document.getElementById("name-of-id"));
Styling an element:
var el = document.getElementById("name-of-id");
// set attribute of an element
el.setAttribute("style", "background-color: blue");
// determine if element has an attribute
el.hasAttribute("style"); // returns true;
// get the value of an attribute
el.getAttribute("style"); // returns "background-color: blue"
// remove an attribute from an element
el.removeAttribute("style");
// get a list of attributes from an element
var list = el.attributes;
// access attribute from list
console.log(list[2]);
Add an event attribute to an element:
var button = document.createElement("button");
// adds a click event to element
button.addEventListener("click", myFunction); // When button is clicked, myFunction will execute
this selects the element or object that is calling a function. this can be passed as a parameter in a function, or used within one.
// this used in a function
el.addEventListener("click", myFunction);
function myFunction()
{
// this represents the element el in this example
this.style.backgroundColor = "blue";
}
// this passed as a parameter
<button onclick=myFunction(this)>Click Me</button>
function myFunction(element)
{
// the button is passed to the function through this
element.style.backgroundColor = "blue";
}
Keyboard events can be triggered using the keywords keydown and keyup.
// Create a keyboard event
body.addEventListener("keydown", myFunction); // myFunction executes whenever a key is pressed
// e represents the key event that is passed to the function
myFunction(e){
console.log(e.key); // if the key q is pressed, returns q
console.log(e.code); // if the key q is pressed, returns KeyQ
}
Animations are a gradual change in an element's style that occurs over time. We can create animations by using setInterval and clearInterval:
// executes the function move once every 1000 milliseconds setInterval(move, 1000); // timers can be set to variables var timer = setInterval(move, 1000); // to end an interval, use the variable as a parameter in clearInterval clearInterval(timer);
jQuery is a JavaScript library that makes DOM traversals more manageable.
To add jQuery to our web pages, we need this link:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
To select and element in the DOM, use the keyword $.
$("body") // selects the body
$(".class") // selects the class class
$("#name") // selects the id name
jQuery comes with it's own functions as well:
// Altering style
$("body").css("background-color", "blue"); // changes body background color blue
// Adding events
$("body").on("click", function);
// Add specific events
$("body").click(function(){});
// Appending to an element
$("body").append("<p>new paragraph</p>");
Iterating through elements with jQuery
// Iterate through elements
$("p").each(function()){
// prints the background color of each p tag element
console.log(this.css("background-color"));
});
// each also has index and element parameters:
$("p").each(function(index, el)){
// prints "Paragraph 0: rgb(0, 0 255)"
console.log("Paragraph " + index + ": " + el.css("background-color"));
});
// animate an element
$("p").animate({"height": "100px"}, "fast"); // changes the height of all p tags to 100px
// hide an element
$("p").hide("slow");
// show an element
$("p").show("fast");
// toggle between hide and show
$("p").toggle("slow");
serializeArray returns form data as a list of data objects. Each data object has two properties - name and value. For example:
<form> <input type="text" name="name"> <input type="text" name="last"> </form>
When $("form").serializeArray() is called, the function will return a list of data objects:
[{name: "name", value: "Text Value"}, {name: "last", value: "Text Value"}]
Where "Text Value" represents the text input by the user.
The .getJSON function returns a JSON object from a URL.
var URL = "https://static1.codehs.com/api/12345/dictionary/english";
$.getJSON(URL, function(data){
// data represents the JSON object requested from the URL
});
We can store data locally in our browser using Local Storage.
We can store values in Local Storage using a key, value notation:
var x = 5;
localStorage.setItem("value", x);
// retrieve the value of x
var val = localStorage.get("value"); // val = 5;
// check if key exists
var hasKey = localStorage.value; // hasKey = 5;
var doesNotHaveKey = localStorage.fake; // doesNotHaveKey = undefined
Storing lists and objects in Local Storage requires the use of JSON to "stringify" the values:
var list = [1, 2, 3];
localStorage.setItem("myList", JSON.stringify(list));
// access a list
var list = JSON.parse(localStorage.getItem("myList"));
Objects are an important data structure that store data in the form of properties and values.
var car = {
make: "Ford",
year: "2009",
numWheels: 4,
makeNoise: function(){
return "vroom!";
},
};
// access properties of an object
car.year; // returns 2009
car.makeNoise(); // returns vroom!