When you write something inside `half of 100 is ${100 / 2}` in a template literal, its result will be computed, converted to a string, and included at that position. The example produces “half of 100 is 50”.
For more info!
When you write something inside `half of 100 is ${100 / 2}` in a template literal, its result will be computed, converted to a string, and included at that position. The example produces “half of 100 is 50”.
var firstName = "John"; var lastName = "Smith"; var fullName = firstName + lastName; document.write("<h1>" + fullName + "</h1>")
Prints
This combines html code and Js variables together. You can concat variables together as well. Variables can also represent lines of code.
creats a popup box with a field to input text that will be saved into a variable
<script> var custinput = prompt("give me your input"); alert(custinput + " is what you told me"); </script>
(44 != 44) || !(33 <= 55)
false & false, no TRUE result on either side so the whole expressino results to FALSE.
!(( 33 !== "33") && !!(33 == "33")), FALSE .
if(condition that's true){ what to do if true; } else { what to do if false; }
<script> var paidMember = prompt("If you are a paid member, then answer Yes") if(paidMember === "Yes") { alert("You answered Yes sooo Welcome to the club!"); } else { alert("Then You're not welcome at this club!"); } </script>
<script> if (condition1) { // block of code if condition1=TRUE } else if (condition2) { // block of code if condition1=FALSE AND condition2=TRUE } else { // block of code if condition1=false AND condition2=FALSE } </script>
var selection = prompt("do you want coffee or tea?") if (selection === "tea") { document.write("Tea is good, do you want lemon with your tea?"); }else if(selection === "coffee") { document.write("Coffee is good, do you want cream & sugar?"); }else { document.write("that is neeither coffee or tea. I don't know what you want.") }
<script> function WhileLoop() { var text =""; var startingNum = 1; while (startingNum < 10){ text += "<p>I AM NUMBER " + startingNum +"!</p>"; startingNum++; } document.getElementById('results').innerHTML =text; } </script>
<script> function doWhileLoop(){ var message=""; var startNum =0; do { startNum++; message += "<p>the number is "+startNum+".</p>" }while (startNum<10); document.getElementById('doWhileResults').innerHTML =message; } </script>
Syntax: for(1 init statement; 1 true condition; 1 incrementation statement) { code to run while true; } <script> function forLoop(){ var message =""; for(var startNum = 0; startNum <10; startNum++) { message += "<p>the number is "+startNum+".</p>"; document.getElementById('forLoopResults').innerHTML =message; } } </script>
functions always have brackets ( ) that come after the fn's name, also the word "function" comes before the fn's name. This pattern will help you spot functions.
function nameOfFunction (arguments, or other functions) {code to run} nameOfFuntion(); //will call function
var inputName = prompt("what is your name?") function greetings (thename){ document.write("hello "+ thename); } greetings(inputName);
function nameOfFn (param1, param2, param3){ fn code;} nameOfFn(arg1, arg2, arg3);
function myFnName(fnArg) { return fnArg; } var fnResultsVar = myFnName("hard coded param") document.write("data contained in the variable named fnResults: " + fnResults)
function myFn1(aString, passthruFn) { alert("first funtion + "+ aString); passthruFn(); } function myFn2() { alert("this is the second fn") } myFn1("a string", myFn2);
function myFn1(aString, passthruFn) { alert("first funtion + "+ aString); passthruFn(); } function myFn2() { alert("this is the second fn") } myFn1("a string", myFn2());
typical fn syntax: setTimeout (myfn, 3000); function myfn(){ alert("this is an alert") } anonymous fn syntax: setTimeout (function () { alert("this is an alert"); }, 3000 );
syntax index0, index1, index2 var food = ["donuts", "coffee", "ice cream"]; or var food = new Array("donuts", "coffee", "ice cream"); how to pull out data from an array syntax food[2]; returns coffee how to change data in an array syntax food[3]="big coffee"; how to find qty of elements in array syntax grab the array's length property food.length returns 3 food[food.length-1]; returns ice cream
var food = ["donuts", "coffee", "ice cream"]; var drinks = ["wine", "wisky", "gin"];
var foodDrinks = food.concat(drinks); joins 2 arrays together. the origional arrays are untouched.
food.push("bread"); adds bread to the end of the food array. it alters the food array.
food.pop(); removes bread from the food array and returns the popped element... bread. it alters the origional array
food.indexOf("coffee"); starts at index0, returns 2 food.indexOf("coffee",3); starts at index3, returns -1
food.unshift("pie"); adds pie to index 0 of the food array. all other elements get moved over, increasing the array size.
calls a fn(makeUpr) on every element in an array(people) and makes a new array(newPeople) with the results. you could addto/removefrom/ 1.e., map a change onto every element in the array using a fn that you create
var people = ["john", "rich", "bill"]; function makeUpr(letters){ return letters.toUpperCase(); //.toUpperCase is a js method } var newPeople = people.map(makeUpr) results in a new array called newPeople = ["JOHN", "RICH", "BILL"]filter method
returns an array made from elements that pass a test performed on another array, leaving the origional array untouched. create a fn to make the test, then call the function using the array's filter method
var numbers = [1, 10, 13, 37]; function over14(number){ return number > 14; } var check = numbers.filter(over14) results in and array called check = [37]
var people = ["john", "rich", "bill"]; // starting point; true/false condition; what 2do if true for(var startNum = 0; startNum < people.length; startNum++) { document.write("< div >" + people[startNum] + " div >"); }
Example: with an named fn
var people = ["john", "rich", "bill"]; function addHTMLtags(text){ document.write ("< div >" + text + "< / div >"); } people.forEach(addHTMLtags);
Example: with an anonymous (ie un-named)fn
var people = ["john", "rich", "bill"]; people.forEach(function(text){ document.write ("< div >" + text + "< / div >"); });
//defining an object var myObject = { firstName: "John", lastName: "Smith", age: 30, notes: "likes Apple" } //reading properties of an object myObject.age; //returns 30 myObject["age"]; //returns 30 //updating properties in an object myObject.age = 25; myObject["age"]; = 25;
Official def: a method is a function that is inside of an object i.e. stored as a property of that object. To access a method inside of an object, you need to call the property within the object like so:
theObject.theProperty( ).
HTML:
A uniquely identified button and div
<button id="btn123">Button #123</button> <div class="onScreen"id="msgBrd123">Output shows up here</div>
Js:
An object containing 3 key/value pairs is initialized. The third key "age"
is paired with an un-named function that returns the numeric value 35.
var anObject123 = { firstName: "Tom", lastName: "Jones", age: function() { return 35; } };
When the Button 123 is clicked, an un-named function runs that grabs the message board div and sets it's text content to the results of running the function paired with the "age" key that is contained in the object known as anObject123.
document.getElementById("btn123").onclick = function(){ document.getElementById("msgBrd123").textContent = anObject123.age(); };
Objects { } are containers the hold multiple key/value pairs. You will come across this when dealing with JSON arrays returned via APIs. Query an object contained within an array like so:
theArray[the desired index number].the key name;
This is an array[ ] that contains two objects{ }. The 1st object is at index 0, the 2nd is at index 1 var anArray = [ {firstname: "Tom", lastName: "Jones",age: 35}, {firstname: "Jane",lastName: "Doe",age: 42}, ];
anArray[0].firstName;
Returns the value paired with the key firstname, located at index 0: "Tom"
anArray[1].firstName;
Returns the value paired with the key firstname located at index 1: "Jane"
Here we have an object{ } that contains 2 Arrays[ ]. Arrats are containers that can hold any data structure including objects{ }. Each item contained within the Arrays separated by a comma and is associated with an index noteing its postion within the Array, starting at index 0.
Paste into the console:
var anObject = { array1: ["Super", "Man", 31], array2: ["Wonder", "Woman", 42] } Paste one of these next and see what happens. anObject.array1[0]; anObject.array2[1];
We will now begin to use Js in a meaningful way, by using Js to manipulate the contents of a webpage by integrating Js with HTML & CSS.
DOM = Document Object Model
The DOM is a separate technology that gives us a hierarchical framework of a webpage to help us target HTML and CSS elements for manipulation with Js. The DOM turns HTML elements into DOM objects (known as nodes). The DOM tree is a hierarical model of the elements on our webpage. Once the html is rendered on the screen, that is the DOM. Your HTML doesn't change but your DOM does.
Using Js code, you can grab specific parts of the DOM by element, text or attribute because each is its own separate node in the tree.
Full list of node types
https://developer.mozilla.org/en-US/docs/Web/API/Node
The most common node types:
The DOM can be organized as a tree, in terms of parent, child & sibiling nodes, which provide the heirarchy we'll take advantage us with our Js code.
is the highest level object and it represents the browser tab but the document obj (ie the web page)is what we're most concerned with.
Using Js, we first grab an HTML element and then use more Js code to do something with what we just grabbed. In this section we'll review several ways of grabing elements on a webpage. We'll put what we've grabbed inside of variables which is best practice as it helps keep our code simple and clean.
HTML: <h1 id="food">Donuts</h1> <ul> <li class="snack">Twisted</li> <li class="snack">Glazed</li> <li class="snack">Filled</li> </ul>
document.getElementById(element id goes here).
Js: var food1 = document.getElementById("food"); Results: <h1 id="food">Donuts</h1> is grabbed and put inside a variable called food1.
document.querySelector(id, class names or element tag).
Selects HTML elements by either id, class name or an element' s tag name. Note: this returns the 1st matching element and it uses CSS syntax as selectors.
var food1 = document.querySelector("#food"); Results: <h1 id="food">Donuts</h1> put into variable food1 var food1 = document.querySelector("li"); Results: <<li class="snack">Twisted</li> put into variable food1
You can console.log(document.querySelector("h1")), or any Js selector to see what it has grabbed via the console.
a better way to debug: var slectdElem = document.querySelector("h1"); console.log(slectdElem); FYIto change what was selected: slectdElem.innerHTML = "what you what to show now";
Element selectors continued
HTML: <h1 id="food">Donuts</h1> <ul> <li class="snack">Twisted</li> <li class="snack">Glazed</li> <li class="snack">Filled</li> </ul>
document.getElementsByTagName()
can select 1 or more elements
var food1 = document.getElementsByTagName("li"); Puts all 3 li elements in an HTMLCollection() HTMLCollection(3) [li.snack, li.snack, li.snack] and puts that into variable food1. HTMLCollections are not arrays but they are similar. Asking for the 1st element is as follows: food1[1]; grabs <li class="snack">Glazed</li>
getElementsByClassName()
same as above but does so by CSS class name
var food1 = document.getElementsByClassName("snack"); grabs an HTMLCollection() same as above.
querySelectorAll()
Can use any CSS selector syntax var food1 = document.querySelectorAll(".snack"); returns all 3 elements in a NodeList(), which is similar to an HTMLCollection() and an Array.
HTML: <h1 id="food">Donuts</h1> <ul> <li class="snack">Twisted</li> <li class="snack">Glazed</li> <li class="snack"><strong>Filled</strong></li> </ul>
by the .textContent method
This method allows us to grab or update the text in an HTML element:
document.getElementById("food").textContent; grabs Donuts in <h1 id="food">Donuts</h1> document.getElementById("food").textContent = "Designer Donuts" grabs Donuts in <h1 id="food">Donuts</h1> and changes it to <h1 id="food">Designer Donuts</h1>
by the .innerHTML method
This method allows us to grab and update the HTML of an element.
document.getElementsByTagName("li")[2].innerHTML; grabs <strong>Filled</strong> document.getElementsByTagName("li")[2].innerHTML; = "<em>Filled</em>"" grabs <strong>Filled</strong> and sets it to <em>Filled</em> This can also be used to add HTML tags where there are none.
<h1 id="coffee">Iced Coffee</h1> <li class="drink">gin</li> <li class="drink">vodka</li> <li class="drink">bourbon</li>Yields:
<div class="onScreen"> <h1 id="coffee2">Iced Coffee</h1> <li class="drink">gin</li> <li class="drink">vodka</li> <li class="drink">bourbon< </div> <script> document.getElementById("coffee2").style.color = "green"; document.getElementById("coffee2").style.backgrounColor = "yellow"; </script>Yields:
<div class="onScreen"> <h1 id="coffee">Iced Coffee</h1> <li class="drinks">gin</li> <li class="drinks">vodka</li> <li class="drinks">bourbon</li> </div> <script> var theDrinks = document.getElementsByClassName("drinks"); for (var i = 0; i < theDrinks.length; i++) { theDrinks[i].style.backgroundColor = "orange"; } </script>Yields:
manipulating a href tags <a href="https://www.apple.com" id="theLink">go to apple</a>
<script> document.querySelector("a").hasAttribute("href"); //returns TRUE/FALSE document.querySelector("a").getAttribute("href"); //grabs "https://www.apple.com" document.querySelector("a").removeAttribute("href"); //removes href document.querySelector("a").setAttribute("href","https://cnn.com"); //sets href </script>
<button onclick="popupFn()">Pop up!</button> <script> function popupFn(){ alert("You clicked me!") } </script>
Keep Js code in another file. HTML Elements need to fully render before Js can be applied so reference your .js file at the bottom of the body. Use getElementById to grab specific elements otherwise the first matching element will be grabbed.
In HTML doc: <button id="meme">Pop up!!</button> at bottom of HTML doc <script src="script.js"></script> In Js.doc: document.getElementById("meme").onclick = function(){ alert("You clicked me!"); }; //Js code selects the button by id and throws an alert box when the button is clicked. Anonympus fns are common in this use case.
Takes 2 arguments, the event & the function. The addEventListener() method attaches an event handler to a specified element, which can be a button, anchor, img or anyting else. You can also assign the code below to a varable and console.log() it to see if it infact grabbed what it was intended to grab. Assigning this code to a variable can also be used to shorten code.
Goto w3schools
In HTML doc: <button id="meme2">Pop up!!</button> In Js.doc: document.getElementById("meme2").addEventListener("click",function(){ alert("You clicked me also!"); });
You can also cause text to change on click.
Make the box change color on click
In HTML doc: //Method1 <button id="abox" style="width: 200px; height: 200px;">Method1 </button> //Method2 <button id="abox2" style="width: 200px; height: 200px;">Method2 </button> In Js.doc: //Method1 document.getElementById("abox").onclick = function(){ document.getElementById("abox").style.backgroundColor ="#"+((1<<24)*Math.random()|0).toString(16); document.getElementById("abox").textContent = "Method1: Color Change." }; var = randomColor = "#"+((1<<24)*Math.random()|0).toString(16); //Method2 document.getElementById("abox2").addEventListener("click",function(){ document.getElementById("abox2").style.backgroundColor = randomColor; document.getElementById("abox2").textContent = "Method2: Color Change." });
Mousing over and past an HTML element. Also look at mouseenter and mouseleave
In HTML doc: <center> <img id="domPic" style="width: 300px; height: auto;" src="assets/images/codeCheets/domModel.png"> </center> In Js.doc: document.getElementById("domPic").onmouseover = function(){ document.getElementById("domPic").setAttribute("src","assets/images/codeCheets/domModel2.png"); }; document.getElementById("domPic").onmouseout = function(){ document.getElementById("domPic").setAttribute("src","assets/images/codeCheets/domModel.png"); };
dynammically finding the remaining characteres in a form field using keyup. Note: keypress is depreciated and doesn't register the backspace key
method1: Using named fn, variables only holding values, results in longer code
HTML: <input type="text" id="usrInput" maxlength="10"><br> <p id="lettersLeft">10 characters left</p> Js: document.getElementById("usrInput").addEventListener("keyup", countLetters); function countLetters(){ var aString = document.getElementById("usrInput").value; var textRemaining = 10 - aString.length; document.getElementById("lettersLeft").textContent = textRemaining + " letters left!" if (textRemaining <= 3) { document.getElementById("lettersLeft").style.color = "red"; } else { document.getElementById("lettersLeft").style.color = "black"; } };
10 characters left
method2:Using anonymous fn and a variable ("textPart") is used to hold a bit of code, results in shorter/cleaner/simplified code
HTML: <input type="text" id="usrInput2" maxlength="10"><br> <p id="lettersLeft2">10 characters left</p> Js: document.getElementById("usrInput2").addEventListener("keyup",function(){ var textlength = document.getElementById("usrInput2").value.length; var textPart = document.getElementById("lettersLeft2"); var numberPart = (10 - (textlength)); textPart.textContent = numberPart + " characters left"; if (numberPart <=3){ textPart.style.color = "red"; } else { textPart.style.color = "black"; }; });
10 characters left
focus means to click on or tab into an element
blur means to click out or tab out of an element..ie to lose focus
HTML: <input type="text" id="clickBox" value="click me 1st"> <div id="msgBoard"</div> Js: var theBox = document.getElementById("clickBox"); var theMsg = document.getElementById("msgBoard"); theBox.addEventListener("focus", function(){ theMsg.textContent="You gave me focus, deleat me now!"; }); theBox.addEventListener("blur", function(){ if (theBox.value == "") { theMsg.textContent = "Everythings a blur, where am I?"; } });
HTML: <img id="carousel" src="assets/images/codeCheets/domModel.png"> Js: var imgArray = ["domModel.png","domModel2.png","domModel3.png"]; var indexImgArray = 0; function swapImage(){ document.getElementById("carousel").setAttribute("src",imgArray[indexImgArray]); indexImgArray++; if (indexImgArray >= imgArray.length) { indexImgArray = 0; }; }; setInterval(swapImage, 2000);