Intro to js
alert('Hello World!')
SHIFT + ENTERalert is using console.log("Hello World")<head> element, before page has loaded<body> element, after page has loaded<script> tags<script> tags (assuming the script file lives in the
same directory as the html doc):<script src="nameofscript.js">
</script>
<script src="nameofscript.js" async></script><script src="nameofscript.js" defer></script>///* */var a;
var a = 4;
typeof variable method to find out what the variabe's datatype isa += 4; => a = a + 4;a++, a--, ++a, --a (last 2 are done before and saved)if (condition is true) {
//execute this block of code
} else {
//execute this code
}
//Test for equality use ==
var a = 5;
var b = "5";
console.log(a == b); //true
//Test for identicle use ===
console.log(a === b); //false
//Not operator !
console.log( a !== b);
console.log( a != b);
//Ternary operator: condition ? true : false
a == b ? console.log("Match") : console.log("No Match");
var colors;
colors = ['red', 'blue', 'green'];
//OR
var colors = new Array('red', 'blue', 'green');
//Quickly copy the contents of an array;
var newArray = colors.splice();
//Named function
function name() {
//code block
return something // to make the function return a value
}
//to call the function
name();
//Anonymous function: function stored in a variable
var anon = function() {
//code block
}
anon();
//Immediately invoked functions
(function() {
//code block
}()) // () immediatley invoked
var parm = new Object();
parm.firstName = 'Parm';
parm.lastName = "Sahadeo";
//Alternative way:
var parm = {
firstName: "Parm",
lastName: "Sahadeo",
eat: function() { //Anonymous function
//does stuff
}
};
parm.eat();
parm.firstName;
function Course(title, instructor, level, published, views) { //capitalize the first letter to suggest a new object
// the arguments will contain all the needed properties of the object
this.title = title; //this refers to the current object
this.instructor = instructor;
this.level = level;
this.published = published;
this.views = views;
this.updateViews = function() {
return ++this.views;
}
}
var object1 = new Course(...);
var object2 = new Course(...);
...
object.title === object["title"]
//Dot notation vs bracket notation
//Dot notation used for simple property name
//Bracket notation used to convert a property name to string to maintain its unique prop name
function doSomeMath() {
var a = 4;
var b = 5;
function multiply() {
var result = a*b;
return result;
}
return multiply;
}
var theResult = doSomeMath(); //returns the multiply function
console.log(theResult()); //returns 20, performs the function multiply
window.innerWidthwindow.open()window.documentdocumentdocument.getElementById('');document.getElementsByClass('');document.getElementsByTagName('html_tag');document.querySelector('selector');: gets the 1st matched elementdocument.querySelectorAll('selector'): gets all the matched elements.querySelector on elements that have been obtained by the .querySelector methoddocument.querySelector().classList.add(class_name) (or .remove(class_name)var element = document.querySelector(".featured-image");
var theImage = element.querySelector("img"); //selects the image under element variable
//Getting an attribute from an element, using .getAttribute("atr")
var altText = theImage.getAttribute("alt");
//Creating a DOM element
var captionElement = document.createElement("figcaption");
//This element is not placed anywhere in the browser, it just sits in the browsers memory
//Create a text node and populate it with the text from the alt attribute above
var captionText = document.createTextNode(altText);
//A text node just contains the text, no actual container/element being used in the html markup
//Append the newly created elements
captionElement.appendChild(captionText);
//ficaption has the text, need to append the figcaption to element
element.appendChild(captionElement);
//set the alt attribute of the image blank, using .setAttribute
theImage.setAttribute('alt', '');
/* Instead of creating the textNode and appending it as a child to the figcaption element
you can use simply, append (appends a string to a specified parent node), the code can
be cleaned up by removing the createTextNode and editing the 2 appendChild methods using
append:
*/
captionElement.append(altText);
element.append(captionElement);
document.querySelector(" ").styledocument.querySelector(" ").style.color = 'blue'
-, convert the word to camel case!
Ex. border-radius becomes borderRadius.style.cssText to insert pure css:
Ex. document.querySelector.style.cssText = "color: white; background-color: blue;"style method, will add on to the already existing styles
document.querySelector('').setAttribute("style", "color: blue")
.setAttribute("style", "color: blue; padding: 1em; border-radius: 50%;").hasAttribute("style"): does the element have this style?.getAttribute("style"): get the inline style.setAttribute("style", "color: red"): add css property.removeAttribute("style"): remove inline stylesvar el = document.querySelector('');
function reveal(e) { //e is the event object
e.preventDefault(); //When the button is clicked, the link takes it to url `/#`
//to stop the page from bouncing back to the top of the page on refresh
//use .preventDefault() to stop the browser from going to this address
el.classList.toggle("hide"); //toggle will remove and add this class each time it is executed
}
el.onclick = reveal;
.onclick calls, they will override one another until the last call is made.eventListeners to your element:var el = document.querySelector();
//el.addEventListener("click", function, false)
el.addEventListener("click", reveal, false);
el.addEventListener("click", function() { console.log("Hi"); }, false);
const CTA = document.query....
function reveal() {
//code
current.innerHTML = ....
//need access to currently clicked object
}
CTA.addEventListener("click", reveal, false);
//Q: How would you pass the currently clicked object?
//A: Need to wrap reveal in an anonymous function:
CTA.addEventListener("click", function() { reveal(this); }, false);
//this refers to the clicked object, which can now be passed as an argument to reveal
//Q: Need to pass the event object, e, also to prevent default refresh to `/#`, how?
//A: You can't just pass e in to reveal, since it is within an anonymous function.
//Remember where the event object is available to you...
//On the call to click!
CTA.addEventListener("click", function(e) { reveal(e, this); });
//Now you can rewrite reveal as:
function reveal(e, current) {
e.preventDefault();
current.innerHTML ...
}