Javascript

<body onload="window.alert('Document is loaded!');">
<!-- beforebegin -->
<p>
  <!-- afterbegin -->
  foo
  <!-- beforeend -->
</p>
<!-- afterend -->

beforeBtn.addEventListener('click', function() {
  var tempDiv = document.createElement('div');
  tempDiv.style.backgroundColor = randomColor();
  if (activeElem) {
    activeElem.insertAdjacentElement('beforebegin', tempDiv);
  }
  setListener(tempDiv);
});

afterBtn.addEventListener('click', function() {
  var tempDiv = document.createElement('div');
  tempDiv.style.backgroundColor = randomColor();
  if (activeElem) {
    activeElem.insertAdjacentElement('afterend', tempDiv);
  }
  setListener(tempDiv);
});
image.src = 'http://placekitten.com/200/300';
image.width = 250;
image.classList.add('cute');
image.alt = 'Cute Kitten';
<!-- beforebegin -->
<p>
  <!-- afterbegin -->
  foo
  <!-- beforeend -->
</p>
<!-- afterend -->

list.insertAdjacentHTML('beforebegin', myDiv);
// GET Request.
fetch('https://api.github.com/users/rich-harris')
  // Handle success
  .then(response => response.json())  // convert to json
  .then(json => console.log(json))    // print data to console
  .catch(err => console.log('Request Failed', err)); // Catch errors
// Get wrapper
const get = async (url, callback) => {   
  const response = await fetch(url)   
  const status = await response.status      
  if (callback) callback[status](await response.json()) 
}  
// Get usage based callback
get(url, {   
  200: body => doSomething,   
  401: body => showSignInModal,   
  403: body => redirectToSafeArea,   
  422: body => showModalWithInstruction 
})
1. Number 
2. String
3. Boolean
4. Undefined
5. Null
6. Symbol (new in ECMAScript 6)
7. Object


!==
===
>=
<=
>
<


var
let (new in ECMAScript 6)
const (new in ECMAScript 6)


if
else
else if
ternary operator
switch


&&
||
!


var a = function name() {}
function name() {}
return
() => (fat arrow function — new in ECMAScript 6)


Array
Object


or
while
do 
forEach (new in ECMAScript 5) 
forin (new in ECMAScript 5) 
forof (new in ECMAScript 5)


LET and CONST variables 
Hoisting variables (LET and CONST) 
Arrow => function short hand 
Arrow functions and THIS
Function default parameter values
Object literals short hand
Rest … operator 
Spread … operator 
For Of Loop
Template literals
Destructing arrays[ ] with default parameters
Destructing {Objects} with alias
var scrollToTopBtn = document.querySelector(".scrollToTopBtn")

var rootElement = document.documentElement

​

function handleScroll() {

  // Do something on scroll

  var scrollTotal = rootElement.scrollHeight - rootElement.clientHeight

  if ((rootElement.scrollTop / scrollTotal ) > 0.0) {
8
    // Show button

    scrollToTopBtn.classList.add("showBtn")

  } else {

    // Hide button

    scrollToTopBtn.classList.remove("showBtn")

  }

}

​

function scrollToTop() {

  // Scroll to top logic

  rootElement.scrollTo({

    top: 0,

    behavior: "smooth"

  })

}

scrollToTopBtn.addEventListener("click", scrollToTop)
const getScrollPosition = (el = window) => ({
  x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
  y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});

// Example
getScrollPosition(); // {x: 0, y: 200}
const scrollToTop = () => {
  const c = document.documentElement.scrollTop || document.body.scrollTop;
  if (c > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, c - c / 8);
  }
};

// Example
scrollToTop();
const detectDeviceType = () =>
  /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
    ? 'Mobile'
    : 'Desktop';

// Example
detectDeviceType(); // "Mobile" or "Desktop"
const getURLParameters = url =>
  (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
    (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
    {}
  );

// Examples
getURLParameters('http://url.com/page?n=Adam&s=Smith'); // {n: 'Adam', s: 'Smith'}
getURLParameters('google.com'); // {}
const copyToClipboard = str => {
  const el = document.createElement('textarea');
  el.value = str;
  el.setAttribute('readonly', '');
  el.style.position = 'absolute';
  el.style.left = '-9999px';
  document.body.appendChild(el);
  const selected =
    document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
  if (selected) {
    document.getSelection().removeAllRanges();
    document.getSelection().addRange(selected);
  }
};

// Example
copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard.
function getBook(bookId) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      let book = {
        title: ‘JavaScript’,
        authorId: ‘123’
      }
    
      resolve(book);
    }, 500);
  });
}
function getAuthor(authorId) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      let author = {
        name: ‘Amy’,
        age: 28
      }
      resolve(author);
    }, 500);
  });
}
async function fetchData() {
  let book = await getBook(2020);
  let author = await getAuthor(book.authorId);
  console.log(author)
}
fetchData(); // { name: ‘Amy’, age: 28 }
// Using {} to create empty objects:
let person = {};
// Using Object() to create empty objects:
let person = new Object();
// Using function constructor:
function Person(name, age) {
  this.name = name;
  this.age = age;
  this.showName = () => console.log(this.name);
}
let person = new Person(‘Amy’, 28);
person.showName();
function Book(title, price) {
  this.title = title;
  this.price = price;
  this.printTitle = () => console.log(this.title);
}
function BookPrototype(prototype) {
  this.prototype = prototype;
  this.clone = () => {
    let book = new Book();
    book.title = prototype.title;
    book.price = prototype.price;
    
    return book;
  };
}
let sampleBook = new Book(‘JavaScript’, 15);
let prototype = new BookPrototype(sampleBook);
let book = prototype.clone();
book.printTitle();
const utils = (function () {
  let instance;
  
  function initialize() {
    return {
      sum: function (a, b) {
        return a + b;
      }
    };
  }
  return {
    getInstance: function () {
      if (!instance) {
        instance = initialize();
      }
      return instance;
    }
  };
})();
let sum = utils.getInstance().sum(3, 5); // 8
const bookModule = (function() {
  // private
  let title = ‘JavaScript’;
  let price = 15;
  // public
  return {
    printTitle: function () {
      console.log(title);
    }
  }
})();
bookModule.printTitle(); // JavaScript

Similiar Collections

Python strftime reference pandas.Period.strftime python - Formatting Quarter time in pandas columns - Stack Overflow python - Pandas: Change day - Stack Overflow python - Check if multiple columns exist in a df - Stack Overflow Pandas DataFrame apply() - sending arguments examples python - How to filter a dataframe of dates by a particular month/day? - Stack Overflow python - replace a value in the entire pandas data frame - Stack Overflow python - Replacing blank values (white space) with NaN in pandas - Stack Overflow python - get list from pandas dataframe column - Stack Overflow python - How to drop rows of Pandas DataFrame whose value in a certain column is NaN - Stack Overflow python - How to drop rows of Pandas DataFrame whose value in a certain column is NaN - Stack Overflow python - How to lowercase a pandas dataframe string column if it has missing values? - Stack Overflow How to Convert Integers to Strings in Pandas DataFrame - Data to Fish How to Convert Integers to Strings in Pandas DataFrame - Data to Fish create a dictionary of two pandas Dataframe columns? - Stack Overflow python - ValueError: No axis named node2 for object type <class 'pandas.core.frame.DataFrame'> - Stack Overflow Python Pandas iterate over rows and access column names - Stack Overflow python - Creating dataframe from a dictionary where entries have different lengths - Stack Overflow python - Deleting DataFrame row in Pandas based on column value - Stack Overflow python - How to check if a column exists in Pandas - Stack Overflow python - Import pandas dataframe column as string not int - Stack Overflow