Snippets Collections
/*  Big O  */

  let performance = performance.now();
  //This can be used to measure the Performance of the code.
  // Use this before the code and after code, It will show the 'performace'


Rules:
 1 : Worst cast
 2 : Remove Constants
 


/* XXXXXXXX--XXXXXX */

/*    */
/* XXXXXXXX--XXXXXX */
/*    */
/* XXXXXXXX--XXXXXX */
/*    */
/* XXXXXXXX--XXXXXX */
/*    */
/* XXXXXXXX--XXXXXX */
/*    */
/* XXXXXXXX--XXXXXX */
/*    */
/* XXXXXXXX--XXXXXX */
/*    */
/* XXXXXXXX--XXXXXX */
/*    */
/* XXXXXXXX--XXXXXX */
/* Lesson 01 : HTML-CSS */

  //Blockquotes
  <blockquote cite="mention Source Link Here">
  <p>Ruh-roh--RAGGY!!!</p>
  <footer>—Scooby Doo, <cite>Mystery Incorporated</cite>         </footer>
  </blockquote>

  //List: Description  ( lists with name/value pairs )
  <dl>
    <dt>Morgawr</dt>
    <dd>A sea serpent.</dd>

    <dt>Owlman</dt>
    <dd>A giant owl-like creature.</dd>
   </dl>
  
                  /*   CSS   */

   //Selecting using attributes
    [attr] { }
    [attr=val] { }
    tag[attr] { }
    tag[attr='val'] { }
    [attr~=val] { }


    -----------------XX------------------------
    
                /*  Javascript  */
    
//Spread Operator.
let nums = [4,5,45,235,523,54,314]
console.log(...nums); //It will only show the numbers, It won't show an array.

//Rest Operator.
const order = [20.17, 18.67, 1.50, "cheese", "eggs", "milk", "bread"];
const [total, subtotal, tax, ...items] = order;
console.log(total, subtotal, tax, items);


 // DOM */

// .innerText: 
It will set/get the  inner text inside the element, But the format will be as shown on the element ( line breaks, spaces will identical to html file.) . It will take CSS into consideration and will return the text that is visibily rendered on the Page. 

//.textContent:
It will set/Get the whole text inside the selected element and it will won't include the line breaks or spaces. 


//Create | Add Text | Append.
let newElem = document.createElement('p');
let data = document.createTextNode("Some Infor..");

newElem.appendChild(data); //Data added to new element.
$("body").appendChild(newElem); // New element added to 'body'

newElem.textContent = 'We can also add text like this...';
----------------------

//insertAdjacentHTML()
: "appendChild()" will always add the data at the end of the element, To resolve this we use 'insertAdjacentHTML()'. It will take 2 arguments. First is the location( one of the 4 method ) and 2nd is the HTML content(text).

Methods:
beforebegin | afterbegin | beforeneed | afterend.

<!--- beforebegin  ---->
  <p>
    <!---  afterbegin ---->
        Existing Text/html content
    <!--- beforeneed  ---->
 </p>
<!---afterend   ---->

**
selectedElem.insertAdjacentElement(methodHere, newElementToAdd);          
          
------------------------

Eg: 
const mainHeading = document.querySelector('#main-heading');
const htmlTextToAdd = '<h2>Skydiving is fun!</h2>';
mainHeading.insertAdjacentHTML('afterend', htmlTextToAdd)

- parentElem.removeChild(childElement); //Pass the element to be deleted in the agument . We can pass the parent element in argument to remove the Parent elem.
- Elem.remove()  //We don't have to mention any arguments.

- Elem.firstElementChild();
- Elem.parentChild();

 // Styling in Javascript */
First Way: 
element.style.property1 = "css stuff";
element.style.property2 = "css stuff";
** Ex:
element.style.width = "50%";
element.style.height = "400px";
**
  
Second Way: ( Better )
element.style.cssText = "width: 50%;padding: 10px 50px;";
Note: "cssText" will overwrite anything that's already in the style attribute  
  
  
 //    Attributes    

element.setAttribute('attribute', attributeValue);

**
aTag.setAttribute('target','_blank');


 //   Classes
Properties:
add() | remove() | toggle() | contains();


elem.className; //It will list all the classes an Combined String.(old way)
or
elem.classList; //It will list all the classes in an ( DOMTokenList ) object.(new way)

elem.classList.add('class-1','class-2',....);//We can assign  single/Multiple classes to the element.

elem.classList.remove('class-1','class-2'); //We can unassign single/multiple classes from the element. 

elemem.classList = 'class-1'; //This will replace all the existing classes assigned to the Element. 

elem.classList.toggle('class1');//to add the class if it doesn't exists or remove it from the list if it does already exist ( other classes are not affected. )

elem.contains('class1'); //returns a boolean based on if the class exists in the list or not


// Events

mouseEvents(document); //It will monitor all the events on docuemnt ( Just for test/practise/fun )

Methods:
addEventListener() | removeEventListener() | dispatchEvent()

addEventListener() and removeEventListener() // Works similarly. ( similar syntax )

//Phases of an Event.
  : Some times events are there on parent and there children. So using Phase events we can change the order ( To fire parent first or the child )

1. Capturing Phase ( parent to child )
  //:It the first phase, Moving from Parent(top) to the selected elem.
 2. At Target Phase  
  // It's the the selected element on which event is attached.
3. Bubbling Phase ( child to parent )
 // It's opposite of capturing, Once the handler is run, It will go back from selected element to the parent element

**
elem.addEventListener('click',()=>{},true)

- By default, It will run in Bubble phase(child first and then parent) .If we pass 3rd argument to 'true' in parentElem.addEventListener()? Then It will run the event in Capturing Phase( Parent will be working first ).


//Node-Name
  //How to know the target element.
if(event.target.nodeName == 'SPAN'){
   //The node name will be always in uppercase.
  takeAction();
}

//To load the HTML content before using the DOM.
document.addEventListener('DOMContentLoaded', function () {
    console.log('the DOM is ready to be interacted with!');
});



**
   {  scrollTo(x, y); }
**  

 /* 
 Lesson 2: Node and Express Environment
 */
  
  > npm list express
  // Return the list of express 'version'. or just check the 'package.json'
  
  
  //Installing packages
  > npm install express
  
  // Express to run server and routes
const express = require('express');

// Start up an instance of app
const app = express();
  

// method '.listen'
const port = 8080;
const server = app.listen(port, listening); //Listening is callback function. 
function listening(){
  console.log("Server runing on Port",port)
}



Methods:
get | post | put | delete

**
  const express = require('express');
  const app = express(); //Creating Instance

  app.get('/', function(req, res ){
    // '/' is the URL Path on the browser. '/' is the           home/root folder on the project.
    // 'request'( Client to server)
    // 'response' ( Server to client )
    res.send("<h1>Jaskaran Singh</h1>");
   })

  app.get('/karan', function(req, res ){
      res.send("<h1>Hi Karan Singh</h1>");
  })
   //It will work for url 'http://localhost:8080/karan'
  
// POST method route
app.post('/', function (req, res) {
  res.send('POST received')
})  

app.listen(8080, ()=>{
    console.log("Runnung....")
   });
**
  // TODO-ROUTES!
app.post('/add', callBack1 )

function callBack1(req, res){
    res.send('Post Received')
  //create a POST route that uses the url /add and sends the response POST received when used to make a request.
}
**
  const data = [];
  app.post('/flavor', addFlavor);

 function addFlavor (req, res) {
  data.push(req.body);
   // A way to store the data
};
**
  let data = []
 app.post('/animal', callBack2 );
 function callBack2(req, res){
  data.push( req.body )   
   //Add a POST route for adding a favorite animal via the path ’/animal’ to an array named data. You will need to create the array as well.
}
**
   /* ------------------------ ------------------*/ 
  
                    /* Async Js */
 : The keyword async before a function makes the function return a promise
  
**
 aync function test(){
   return "Some results...";
   // Since we are using 'aync', test() will be a            asynchrounous function.
 }   
> test(); //It will return a 'pending' Promise
> test().then((res)=>{},(rej)=>{})
**   
**
  const retrieveData = async (url='') =>{ 
  const request = await fetch(url);
  try {
  // Transform into JSON
  const allData = await request.json()
  }
  catch(error) {
    console.log("error", error);
    // appropriately handle the error
  }
}
**
  
//Server and Client side.
//Async Js.

**
const express = require('express');
const app = express();

//Movie Empty List.
let fakeData = {
    animal : 'lion', fact : 'lions are fun'
};
app.get('/fakeAnimalData', getFakeData );
function getFakeData(req, res){
 res.send(fakeData)
}
app.listen(8080, ()=>{
    console.log("Runnung....")
});
// 'localhost:8080/fakeAnimalData'  will return 'fakeData' Object

**
  /*    Chaining Promises    */
  
  
  
 
   /* ------------------------ ------------------*/ 
   /* ------------------------ ------------------*/ 
 

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension