//------------************ app.js*********************
// // //Variable- Most basic cbuilding block
// // //Variables-Store,Access, Modify== Value
// // //Declare,Assignment ,Operator and Assign value
// // //let name; - with assigning name value- it will show undefined . To fix this add empty string as below
// // let name="Bal Mukund Bangalore";
// // let address,zip,state;
// // console.log(address);
// // //Assign value later
// // address = "Maruthi Layout, AECS Layout"
// // zip = 560037;
// // state = "karnatka";
// // console.log(address,zip,state);
// // //Modify exisitng
// // name = "Barnali Sarmah"
// // console.log(name);
// // // Naming convention for variable
// // //can contain digits,letters,underscore,$
// // //must start with letter, $ or underscore - can not start with number
// // //camelcase or underscore
// // //case sensitive -fullname vs Fullname
// // //let 1name= "Bal"; // Error- an identifier or keyword can not immediately follow a numeric literal(invalid or unexpected token)
// // //let let name ="Bal" // Error - let is disallowed as a lexically bound name
// // // javascript stops executing if there is an error in earlier line
// // //console.log(fullName) // if variable is not define but trying to print/access , throws error - Uncaught ReferenceError : fullName is not defined
// // //-----*****Number data type******------////
// // //Loose Typed = don't declare type
// // //Number displayed in console should be in blue
// // let number = 34;
// // let pants =2.45;
// // pants ='are great';
// // number +=10; // Add 10 in number value
// // console.log(pants);
// // console.log(number);
// // // Any input value from html element - by default captures as string
// // //----Data types- **** ---//
// // //Primitive - String,Number,Boolean,Null,Undefined,symbol
// // //String
// // const text1 ='some text'
// // //Number
// // const a= 5;
// // //Boolean
// // let value1=true;
// // //null
// // const result1 =null;
// // //undefined
// // let y;
// // //Object - Arrays, Functions , Objects
// // //Array -[] ,0 index based
// // const friend = ['john','peter','Rashmi',45,undefined,null]
// // let bestFriend =friend[2];
// // friend[1] = "Rohan";
// // console.log(friend[1]);
// // //function
// // //function declaration
// // function hello(){
// // console.log("hello"+ friend[0]);
// // }
// // hello();//call/invoke function hello
// // //parameter/argument of function
// // //sample - greet only Rasmhmi
// // function greet(name) // no need to pass data type under argument. Also argument under parenthesis is local variable
// // //name variable can not be accessed outside this function
// // {
// // console.log('Hello there ' +name);
// // }
// // console.log('Hello there ' +name);
// // greet("Bob");
// // greet("Ana");
// // //two arguments
// // function greet(name,second)
// // {
// // console.log(second);
// // console.log("Hello there" +name);
// // }
// // greet('peter ', 'rashmi');
// // //function Expression
// // const add =function(a,b){ // without name of function is anonymous function
// // //const add =function sum(a,b) {return a+b;} //function expression with name of function
// // return a+b;
// // }
// // //Invoke- function with name
// // const thirdValue= add(5,6) // Any new vriable with any name and pass the value under variable name i.e add here
// // //Objects
// // // Objects- key/value pairs methods
// // //dot notation
// // //Example:
// // const person={
// // name:'Bal',
// // age: 40,
// // lastName :'Mukund',
// // education: false,
// // married: true,
// // siblings:['anand','Manish'], //multivalue property i.e array (same sytax as array)
// // // In ESC6 - below functio can also be added without keyword function keyword -directly by function name
// // //i.e greeting(){}
// // greeting: function(){ //function under property name . Can add name of function or keep it anonymous as it is
// // console.log("Hello my name is Bal Mukund"); //statement ends with semi colon
// // },
// // };
// // //method - calling function (part of object) by dot notation is called as method as below-
// // person.greeting(); //calling function i.e object method
// // console.log(person.lastName);//accessing object propery
// // //assign object propery to new variable
// // const age= person.age;
// // console.log(age); // access new variable
// // //type of - operator (type of variable) or (type of value)
// // //const x =5;
// // //console.log(typeof x);
// // //console.log(typeof 5);
// // // -------------------------------------------------------------
// // // COnditional logic
// // // If
// // const value =2; //assign variable
// // const num2 =10;
// // if(value){ //boolean i.e value =2 ,true or false. Since value =2 is assigned it will set true and execute statement under if otherwise else
// // console.log("if condition holds true")
// // }
// // else{
// // console.log("if condition is false")
// // }
// // //If condition for two variable comparison
// // //Important note: else condition is set (if condition false ) no matter whether else condition is applicable or not(i.e else will always execute if(if condition) fails)
// // if(value>num2){
// // console.log(value + " is greater than "+ num2);
// // }
// // else{
// // console.log(num2 +" is greater than " + value)
// // }
// // // !(not condition)
// // const value3 =true;
// // if(!value3){
// // console.log("Value is true");
// // }
// // else{
// // console.log("value is false");
// // }
// // // Equality operator
// // // ==(double equal) checks for equal value
// // //===(triple equal) checks for data type and equal value
// // //double = example below
// // const equalCheck = 10;
// // const equalCheck2= "10"
// // if(equalCheck == equalCheck2){
// // console.log(equalCheck2 +" is equal to(using double equal==) " +equalCheck)
// // }
// // else{
// // console.log(equalCheck2 +" is NOT equal to(using double equal ==) " +equalCheck)
// // }
// // //triple equal example below
// // const equalCheck3 = 10;
// // const equalCheck4= "10"
// // if(equalCheck3 === equalCheck4){
// // console.log(equalCheck3 +" is equal to(using ===) " +equalCheck4)
// // }
// // else{
// // console.log(equalCheck3 +" is NOT equal to (using triple equal ===)" +equalCheck4)
// // }
// // // Logical Operators
// // // (|| - OR), (&& - AND)
// // //OR(||) operator
// // const fullName ="peter";
// // const ageInYears =24;
// // if(fullName=='bob' || ageInYears=='24'){
// // console.log('hello there user');
// // }
// // else{
// // console.log("wrong values");
// // }
// // //AND(&&) operator
// // if(fullName!=='bob' && ageInYears==='24'){
// // console.log('hello there user');
// // }
// // else{
// // console.log("wrong values");
// // }
// // // String properties and methods
// // // wrapper String Object, don't memorize methods
// // let text = ' Peter Jordan';
// // let result = text.length;
// // console.log(result);
// // console.log(text.length);
// // console.log(text.toLowerCase());
// // console.log(text.toUpperCase());
// // console.log(text.charAt(0));
// // console.log(text.charAt(text.length - 1));
// // console.log(text.indexOf('e'));
// // console.log(text);
// // console.log(text.trim());
// // console.log(text.trim().toLowerCase().startsWith('peter'));
// // console.log(text.includes('eter'));
// // console.log(text.slice(0, 2));
// // console.log(text.slice(-3));
// // // const person = {
// // // name: 'peter', // property
// // // greeting() {
// // // // method
// // // console.log("Hey, I'm Peter");
// // // },
// // // };
// // // console.log(person);
// // // console.log(person.name);
// // // person.greeting();
// // //------------------*********-------------------------------
// // // Template Literals - ES6+
// // //Back-tick characters -``(above tab)
// // //interpolation ${} - insert expression(value)
// // const name1 ="Mukund";
// // const age1 = 34;
// // //use template literals
// // const value2=`Hey it's ${name1} and my age is ${age1}`;
// // //without using template literals -traditional way
// // //const value2="Hey it's " +name+ " and my age is " +age
// // console.log(value2);
// // // Arrays and for loop
// // const names = ['Mukund','Barna','Briti'];
// // const lastName = 'Sarmah';
// // let newArray=[];
// // //for loop
// // for(let i=0;i<names.length;i++){
// // //console.log([i]);
// // console.log(`My full name is ${names[i]} ${lastName}`);
// // //console.log("My full name is" +names[i]+ " "+lastName);
// // }
// // //Function,return,if ,arrays,loop . Usecase: Calculate total of all the bills
// // //Define array for grocery bill
// // const grocery =[10,90,200,78,900,310,445,657];
// // const medicines =[575,240,350,650,750,200];
// // const cab=[150,250,675,85]
// // function billTotal(listItems){
// // let total=0;
// // for(i=0;i<listItems.length;i++){
// // total = total+listItems[i]
// // }
// // return total;
// // }
// // const groceryTotal=billTotal(grocery);
// // const medicineTotal=billTotal(medicines);
// // const cabTotal=billTotal(cab);
// // console.log({
// // grocery : groceryTotal,
// // medicine: medicineTotal,
// // cab: cabTotal
// // }
// // )
// // // Null and undefined , both represent "no value"
// // //undefined- "javascript can not find value for this"
// // //variables without value
// // //missing function argument
// // //missing object properties
// // //null -developer sets the value
// // let number4 = 20 + null;//20+0;
// // console.log(number4);
// // let number5= 20 + undefined;//20 + 0;
// // console.log(number5);
// // //Variable lookup
// // //{} - code block variable
// // //global variable
// // const globalNumber =5;
// // function sum(num1,num2){
// // const globalNumber =20;
// // const result= num1 + num2 + globalNumber;//Javascript starts use of local variable. If local variable not found then pick global variable
// // return result;
// // }
// // console.log(sum(3, 4));
// //Functions are first call objects-stored in a variable(expression),passed as an argument to another function ,return from the function
// //callback function, Higher order function i.e call function with argument as function
// //function getting passed is callback function.
// //Higher order function- accepts another function as argument(returns another function as result)
// // Thumb rule- Higher order function should not be modified . Instead create new callback function
// //callback function
// function morning(name9) {
// //callback function
// return `Good Morning ${name9}`;
// console.log(`name`);
// }
// function afternoon(name9) {
// //callback function
// return `Goood Afternoon ${name9}`;
// }
// function evening(name9) {
// //call back function
// return `Goood Evening ${name9}`;
// }
// //Higher order function
// function greet(name9, cb) {
// //argument passed as cb i.e function. During invoking morning function(callback) is passed
// const myName = "Mukund";
// console.log(`${cb(name9)}, my name is ${myName}`);
// }
// greet("bobo", morning);
// greet("Mukund", afternoon);
// greet("Brti", evening);
// //powerful Array methods - forEach,filter,find,reduce
// //Iterate over array- no for loop required
// //Accept CALLBACK function as argument ,calls callback against each item in array .Reference item in callback parameter
// //forEach - does not return new array
// const group = [
// { name: "Adam ", age: 34, profession: "Content Writer" },
// { name: "Rod ", age: 34, profession: "Model" },
// { name: "Steve ", age: 3, profession: "Manager" },
// ];
// const people = [
// { name: "John ", age: 34, profession: "private", salary: 10000 },
// { name: "Rod ", age: 34, profession: "Software", salary: 5000 },
// { name: "Susy ", age: 3, profession: "Government", salary: 900 },
// ];
// function showPerson(person) {
// // for manipulation on variable within function- pass argument
// console.log(`My name is ${person.name} and my age is ${person.age}`);
// }
// people.forEach(showPerson);
// // map - returns a new array
// //does not change size of original array
// const ages = people.map(function (person) {
// return person.age + 10;
// });
// console.log(ages);
// //create variable of object type
// const newPeople = people.map(function (person) {
// return {
// firstName: person.name.toUpperCase(),
// oldAge: person.age + 20,
// Job: person.profession,
// };
// });
// console.log(newPeople);
// const names = people.map(function (person) {
// return `<h1>${person.name}</h1>`;
// });
// document.body.innerHTML = names.join("");
// console.log(names);
// //-------------
// //Continue after Map--
// //------------
// // filter - does return a new array
// //can manipulate the size of array
// //return based on condition - if condition does not match then empty array
// const youngpeople = people.filter(function (person) {
// return person.age >= 25;
// });
// const job = people.filter(function (post) {
// return post.profession == "Software" || post.profession == "private";
// });
// console.log(job);
// console.log(youngpeople);
// //find -returns single instance(in this case object)
// //returns first match if condition is true , else returns undefined
// //great for getting unique value
// const devInstnace = people.find(function (instance) {
// return instance.age >= 25;
// });
// console.log(devInstnace);
// console.log(devInstnace.name);
// //reduce method - reduces to single value -number,array ,object
// // 1 parameter ('acc') - total of all calculations(initial value)
// //2 parameter('curr') - current iteration/value
// const totalSaray = people.reduce(function (acc, currentItem) {
// //two parameteers, acc for initialization and currentItem for current Value
// acc += currentItem.salary;
// return acc;
// }, 0); //,o is to initialize with zero
// console.log(`Total salary is ${totalSaray}`);
// //Math Object - Standard built in object
// const number1 = 5.66;
// const roundNum = Math.floor(number1);
// console.log(roundNum);
// const randomLast = Math.abs(Math.floor(Math.random() * 6) + 1); //range always remains till tcounts.Fix this.what bout if I want to make from 1 to 6 only
// console.log(`Ludo ${randomLast}`);
// //Date - global Object
// days = [
// "Sunday",
// "Monday",
// "Tuesday",
// "Wednesday",
// "Thursday",
// "Friday",
// "Saturday",
// ];
// months = [
// "Jan",
// "Feb",
// "March",
// "Apr",
// "May",
// "June",
// "July",
// "Aug",
// "Sep",
// "Oct",
// "Nov",
// "Dec",
// ];
// const date = new Date();
// console.log(date);
// //All Date method returns the value in number form i.e 1,2,3
// day = date.getDay();
// date1 = date.getDate();
// month = date.getMonth();
// hour = date.getHours();
// minute = date.getMinutes();
// second = date.getSeconds();
// check = date.toLocaleString();
// clock = `Today is ${days[day]} ,${date1} ${months[month]} and time is ${hour} : ${minute} : ${second} `;
// console.log(clock);
// document.writeln(clock);
// console.log(`Locale String check ${check}`);
// //----------------------------*****************-------------------------------------
// //Document Object Model
// //Similar to CSS - select element or group of elements that you want to affect
// //Decide the effect we want to apply to the selection
// //Many different ways-
// document.body.style.backgroundColor = "blue";
// //select element
// //document.getElementById('btn').style.color='yellow';
// //select element using css-query selector
// //document.querySelector('element').style.color='red';
// //assign element to variable once and apply the effect whenver want
// //const element1=document.querySelector('element');
// //const element2=document.querySelectorAll('element');
// //window object of browser not object of javascript. window is current open tab
// //console.log(window);
// //retuns a node or nodelist(array like object)
// //to get nodeName
// //const list1= btn.nodeName;
// //console.log(list1);
// //TO access window method say - alert , it should be written as below
// //window.alert("hello");
// //however if javascript does not find method it always look in window object
// //alert("hello");
// //To find attribute and method of node use dir(method) of console to node as below
// //console.dir(document);
// //------------------------*********Navigate the DOM-Children ******************----------------
// //childNodes - returns all childNodes including white space which is treated as text node. Examples: NodeList(8) [h1, h1, h1, text, comment, text, script, text]
// //children
// //firstChild
// //lastChild
// //Important note- node selection,append,removal happens on page rendered element and not necessarily the html element in file
// const result1 = document.querySelector("h1");
// const parent = result1.parentElement.parentElement;
// parent.style.color = "red"; // Applies color to parent element
// console.log(result1);
// console.log(result1.parentElement);
// console.log(result1.parentElement.parentElement);
// console.log(result1.children);
// console.log(result1.childNodes);
// //prviousSibling,nextSibling - (can return whitespace too) extract the previous or next sibling of selected element
// //previousElementSibling ,nextElementSibling(does not retun whitespace)
// // const first = document.querySelector("h1");
// // const third = first.nextSibling;
// // third.style.color = "pink";
// // const fourth = third.nextSibling;
// // const prevFourth = fourth.previousSibling;
// console.log(third);
// console.log(fourth);
// console.log(prevFourth);
// console.log(third.nextElementSibling);
// //nodeValue and textContent - to display text content
// console.log(fourth.childNodes[0].nodeValue); //nodeValue gets applied on specific node(if node value present)
// console.log(fourth.firstChild.nodeValue);
// console.log(third.textContent); //displays text of element/node
// //getAttribute, setAttribute - extract or set attribute of element(i.e class ,id,href etc)
// //const headerAll = document.querySelectorAll('h1');
// //const idValue=headerAll.getAttribute('id');//extracting id of headerAll element
// //console.log(headerAll);
// fourth.setAttribute("id", "last"); //setting id to list item
// fourth.setAttribute("class", "last"); //setting class to list item
// //classList(append class), className(override class)- Add/apply css class to element dynamically
// const findClass = fourth.className;
// console.log(findClass);
// fourth.classList.add("red", "blue"); //append class addition to what defined. Also append multiple class with comma separated value
// console.log(fourth.classList);
// fourth.classList.remove("blue"); //remove class from element
// //check if class is present or not for an element - classList.contains
// const result = fourth.classList.contains("last");
// if (result) {
// console.log("Verified- last class is present");
// }
// //fourth.className='red'; //overrides class
// console.log(fourth.className);
// //createElement(element),createTextNode(text content),appendChild
// // const emptyElement = document.createElement("div"); //create blank div .
// //create text node
// // const textNode = document.createTextNode(
// // "This is simple text node created by createTextNode"
// // );
// // emptyElement.appendChild(textNode); //attch text node newly created div
// //document.body.appendChild(emptyElement); //attach the text+div to html i.e document attached last element
// //appendChild to an element instead of body
// fourth.appendChild(emptyElement);
// // If want to add element before another element
// //insertBefore('element','location')
// // const heading5 = document.createElement("h1");
// // const text = document.createTextNode("adding h1 element");
// // heading5.appendChild(text);
// // document.body.insertBefore("heading5", "fourth");
// //innerText,prepend
// const heading6 = document.createElement("h2");
// heading6.innerText = `I am dynamic heading`;
// document.body.prepend(heading6);
// //remove,removeChild
// const headingResult = document.querySelector(".last");
// const result2 = headingResult.querySelector("div");
// console.log(result2);
// //result2.remove(); // removes the result2 from document i.e div is removed
// //headingResult.removeChild(result2); //removes the child i.e div element only from last class element
// //innerHTML,textContent
// console.log(result2.textContent);
// console.log(headingResult.innerHTML);
// const ul = document.createElement("ul");
// ul.innerHTML = ` <li class="item"> First link</a></li>
// <li class="item">Second link</a></li>
// <li class="item">Third link</a></li>`;
// document.body.appendChild(ul);
// //--------------*******----------------------------------
// //Change CSS with style property
// const randomList = document.querySelectorAll(".item");
// //randomList.style.color = "green";
// randomList.forEach(function changeColor() {
// randomList[1].style.color = "green";
// });
// //--------------*******-----------
// //Events
//---------------------------------
//Events overview-
//1. Select event
//2.add event listener(pass argument)
//3. what event and what to do
//Click Event
const btn = document.querySelector(".btn");
//aonymous call back function
//btn.addEventListener("click", function () {
//btn.classList.add("blue");
// btn.style.backgroundColor = "green";
//});
//function reference
function changeColor() {
let hasClass = btn.classList.contains("red");
if (hasClass) {
btn.style.color = "green";
} else {
btn.classList.add("blue");
}
}
btn.addEventListener("click", changeColor);
//Mouse Events
//click - fires after full action occurs
//mousedown - button is pressed
//mouseup - button is released
//mouseenter - mouse on to an element
//mouseleave - moved out of an element
btn.addEventListener("click", function () {
console.log("You clicked me");
});
// btn.addEventListener("mousedown", function () {
// console.log("You mousedown");
// });
btn.addEventListener("mouseup", function () {
console.log("You mouseup");
});
btn.addEventListener("mouseenter", function () {
btn.classList.add("blue");
});
btn.addEventListener("mouseleave", function () {
btn.classList.remove("blue");
});
//Key Events
//keypress - when key is pressed
//keydown - when key is down
//keyup - when key is up
const nameInput = document.getElementById("name");
console.log(nameInput);
nameInput.addEventListener("keypress", function () {
nameInput.classList.add("red");
});
// nameInput.addEventListener("keydown", function () {
// nameInput.classList.add("blue");
// });
nameInput.addEventListener("keyup", function () {
nameInput.classList.add("red");
console.log(nameInput.value);
});
//---------------------------------------------------------------------
//Event Object - event object argument e,evt
//info about trigger event
//event.type
//event.currentTarget
//this keyword
//preventDefault() - prevents default behavior
//const heading1 = document.querySelector("h1");
const link = document.getElementById("link");
btn.addEventListener("click", function (event) {
event.currentTarget.classList.add("red"); //same behavior as btn.classList.add("red") , we can also traverse elemenTarget
console.log(event.type);
console.log(this); //this keyword does not work with arrow function
});
function someFunc(e) {
console.log("link clicked");
//e.preventDefault(); //usually done for page refresh(form submission) or link click to prevent default behavior
}
link.addEventListener("click", someFunc);
//currentTarget vs target
//currentTarget - always refers to element to which event handle has been attached to(nested element will get impacted)
//target - identifies the element on whichevent has occured
//---------****************-------------------------------------------
//Javascript Event propogation: Bubbling and capturing
//allows select dynamic elements - fire event without selecting the element
//event propogation - order of events are fired
//event bubbling -clicked element first then bubbles up -default
//event capturing - fires at the root and fires until reaches target
const container = document.querySelector(".container");
const list = document.querySelector(".list-items");
function showBubbling(e) {
console.log("current Target", e.currentTarget);
console.log("Target is ", e.target);
//check if selected/clicked element is link-
if (e.target.classList.contains("link")) {
console.log("link clicked");
}
}
function stopPropogation() {
console.log("you fired stop propogation");
}
//list.addEventListener("click", stopPropogation); //stop bubbling
//using event listener accessing elements within that-parent or child by target or currentTarget
//always fires from lowest(nested bubble) up to chain/parent i.e always last event will fire first then container
container.addEventListener("click", showBubbling, { capture: true });
list.addEventListener("click", showBubbling, { capture: true });
document.addEventListener("click", showBubbling, { capture: true });
window.addEventListener("click", showBubbling, { capture: true }); //capture :true sets the ordering event from parent to child
//--------------******Submit Event Listener**********-----------------
//preventDefault
//how to get a value(using value property )
const form = document.getElementById("form");
const name = document.getElementById("name");
const password = document.getElementById("password");
form.addEventListener("submit", function (e) {
e.preventDefault();
console.log("form submitted");
console.log(name.value);
console.log(password.value);
});
//Locale Storage ----------**********
//Web storage API - provided by browser
//session storage(persist data while tab is open),local storage(persist between opening and closing of browser)
//setItem, getItem, removeItem,clear
localStorage.setItem("name", "john"); //second instance overrides the first instance
sessionStorage.setItem("name", "Ram");
localStorage.getItem(name);
//local storage with multiple values
//JSON.stringify() - make in to json string
//JSON.parse();
const friends = ["John", "David", "Bryce", "Kale"];
//localStorage.setItem("friends", JSON.stringify(friends)); //use JSON.stringify in array as strings
const values = JSON.parse(localStorage.getItem("friends"));
let fruits;
if (localStorage.getItem(fruits)) {
fruits = JSON.parse(localStorage.getItem("fruits"));
} else {
fruits = [];
}
fruits.push("apple");
console.log(fruits);
----------------------------------------------------------------------------------------------------------------------------