Last active
December 6, 2017 22:21
-
-
Save banhaclong20/389a34c44e706f37699fd84d2714fffd to your computer and use it in GitHub Desktop.
Vanilla JS Simple Cheatsheet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Grab Children/Parent Node(s) */ | |
var parent = document.getElementById('container'); | |
var children = parent.childNodes; | |
var parentNode = children.parentNode; | |
/* Create New DOM Elements /* | |
var newH1 = document.createElement('h1'); | |
var newPara = document.createElement('p'); | |
var h1Text = document.createTextNode('This is text for h1'); | |
var paraText = document.createTextNode('Text for paragraph'); | |
newH1.appendChild(h1Text); | |
newPara.appendChild(paraText); | |
parentNode.insertBefore(h1Text, paraText) // Insert h1 text before para text | |
/* Add Element to the DOM /* | |
var container1 = document.getElementById('ct1'); | |
var container2 = document.getElementById('ct2'); | |
container2.insertAdjacentHTML('beforebegin', '<div><span>This is the inserted content</span></div>'); | |
// beforebegin: The HTML would be placed immediately before the element, as a sibling. | |
// afterbegin: The HTML would be placed inside the element, before its first child. | |
// beforeend: The HTML would be placed inside the element, after its last child. | |
// afterend: The HTML would be placed immediately after the element, as a sibling. | |
/* Contains/Add & remove multiple class */ | |
container1.classList.add('class1', 'class2'); // Use the same for remove | |
container1.classList.contains('class1'); // Will return true if its has class class1 or false | |
/* Add/Remove Array */ | |
var emptyArr = []; | |
var arr = [emtyArr, true, 2, "Random String"]; | |
arr.push('new string'); // Add to end of Array or you can use this arr[arr.length] = 'new string'; | |
arr.pop(); // Remove last item and return the removed item | |
arr.shift(); // Remove first item | |
arr.unshift(1); // Add 1 to beginning of array and return new length | |
arr.splice(2, 1); // First arg is where to start and second is how many things to splice. | |
/* Events */ | |
var newEle = document.getElementById('id'); | |
newEle.onclick = function() { | |
console.log('clicked'); | |
}; | |
newEle.addEventListener('focus', function(e) { | |
console.log('focused'); | |
}, false); | |
newEle.removeEventListener('focus', function(e) { | |
console.log('focused'); | |
}, false); | |
window.onload = function() { | |
console.log('Loaded'); | |
}; | |
/* Timers */ | |
function simpleMessage() { | |
alert("This is just a simple alert"); | |
} | |
// set time out | |
window.setTimeout(simpleMessage, 5000); | |
// if you wanted to clear the timer. | |
var timer = window.setTimeout(simpleMessage, 5000); | |
window.clearTimeout(timer); | |
// set interval. will repeat every 5000ms | |
window.setInterval(simpleMessage, 5000); | |
// if you wanted to clear the intervals. | |
var intervalHandler = window.setInterval(simpleMessage, 5000); | |
window.clearInterval(intervalHandle); | |
/* Debounce js */ | |
function debounce(func, wait, immediate) { | |
var timeout; | |
return function() { | |
var context = this; | |
var args = arguments; | |
var later = function() { | |
timeout = null; | |
if (!immediate) func.apply(context, args); | |
}; | |
var callNow = immediate && !timeout; | |
clearTimeout(timeout); | |
timeout = setTimeout(later, wait); | |
if (callNow) func.apply(context, args); | |
}; | |
}; | |
/* DOM onload ready */ | |
// The browser fully loaded HTML, and the DOM tree is built, but external resources like pictures <img> and | |
// stylesheets may be not yet loaded. | |
document.addEventListener('DOMContentLoaded', function() { | |
console.log('DOM is ready'); | |
}, false); | |
// The load event on window object trigger when the whole page is loaded,including styles, images and other resources. | |
window.onload = function() { | |
alert('Page loaded'); | |
// image is loaded at this time | |
alert(`Image size: ${img.offsetWidth}x${img.offsetHeight}`); | |
}; | |
//If a visitor initiated leaving the page or tries to close the window, | |
//the beforeunload handler can ask for additional confirmation. | |
window.onbeforeunload = function() { | |
return "There are unsaved changes. Leave now?"; | |
}; | |
/* Load event */ | |
let script = document.createElement('script'); | |
// can load any script, from any domain | |
script.src = "https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.3.0/lodash.js" | |
document.head.append(script); | |
script.onload = function() { | |
// the script creates a helper function "_" | |
alert(_); // the function is available | |
}; | |
/* get the value of the data-modal attribute from the button */ | |
<a href="" data-modal="#modal" class="modal__trigger">Modal 1</a> | |
var self = this; | |
// get the value of the data-modal attribute from the button | |
var modalId = self.dataset.modal; | |
var len = modalId.length; | |
// remove the '#' from the string | |
var modalIdTrimmed = modalId.substring(1, len); | |
// select the modal we want to activate | |
var modal = document.getElementById(modalIdTrimmed); | |
/* Working with scroll */ | |
document.addEventListener('wheel', scrollPage); | |
// Get the Nodename | |
e.target.nodeName | |
// Get the next/previous sibling | |
var next = e.target.nextElementSibling; | |
var prev = e.target.previousElementSibling; | |
// If can't find nodeName, using this | |
var next = e.target.closest(nodesName).nextElementSibling; | |
var prev = e.target.closest(nodesName).previousElementSibling; | |
// Check of scroll to up or down | |
e.deltaY < 0 // Scroll up | |
e.deltaY > 0 // scroll down | |
// Check the position of a window | |
window.pageYOffset; | |
// Check the Height of the body window | |
document.body.scrollHeight, | |
document.body.offsetHeight, | |
document.documentElement.clientHeight, | |
document.documentElement.scrollHeight, | |
document.documentElement.offsetHeight | |
/* Working with scroll */ | |
window.addEventListener('touchstart', function onFirstTouch() { | |
// we could use a class | |
document.body.classList.add('user-is-touching'); | |
// or set some global variable | |
window.USER_IS_TOUCHING = true; | |
// or set your app's state however you normally would | |
myFrameworkOfChoice.dispatchEvent('USER_IS_TOUCHING', true); | |
// we only need to know once that a human touched the screen, so we can stop listening now | |
window.removeEventListener('touchstart', onFirstTouch, false); | |
}, false); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment