Skip to content

Instantly share code, notes, and snippets.

@JeansBolong
Last active November 5, 2021 04:26
Javascript CheatSheet
//anonymous fucntion
((a,b) => console.log(a+b))(5,2);
function getImages(){
return promise = new Promise(function (resolve,reject) {
axios.get(url)
.then(function (response) {
// handle success
data = config.domain+"/images/"+response.data.content.imagePreview;
resolve (data);
})
.catch(function (error) {
// handle error
reject(error)
})
})
}
async function fillImage() {
imagePrev = await getImages()
.then(() => { console.log("everything is ok") })
.catch(err => { console.log(err) });
}
fillImage();
//btn scroll to top
$(".btn-scroll-top").on("click", function(){
$('html, body').animate({scrollTop : 0},800);
return false;
});
//btn scroll to some div
$("html, body").animate({ scrollTop: $("target").offset().top }, 200);
atau pake function ini
function topFunction() {
document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}
function titleCase(str) {
var words = str.split(" ");
var newArray = [];
for(var i=0; i < words.length; i++){
newArray.push(words[i].slice(0,1).toUpperCase() + words[i].slice(1).toLowerCase());
}
return newArray.join(" ");
}
titleCase("I'm a little tea pot");
console.log("%c KABOOOMMMMM.....",
"color: rgb(235, 50, 50); " +
"font-size: 32px; font-family: 'Arial', sans-serif !important; font-weight: bold; font-style:italic");
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
//ref: https://www.quirksmode.org/js/cookies.html
<!-- exit-intent popup into action -->
<style>
#exitDetect{
position: fixed;
width: 100%;
height: 100%;
visibility: hidden;
z-index: 10002;
top: 0;
opacity: 0;
transform: scale(0.5);
transition: transform 0.2s, opacity 0.2s, visibility 0s 0.2s;
margin: 0 auto;
text-align: center;
box-shadow: 0 1px 10px rgba(0, 0, 0, 0.5);
background: #862a5c;
padding-bottom: 100px;
padding-top: 50px;
color: #fff;
font-size: 2rem;
}
</style>
<script>
let showed = false;
const show = () => {
if (showed) return;
if (
document.cookie.split(";").filter((item) => {
return item.includes("popup=");
}).length
) {
return;
} else {
console.log(
document.cookie.split(";").filter((item) => {
return item.includes("popup=")
}).length
)
console.log(document.cookie.split(";"))
}
document.cookie = "popup=true;path=/;max-age=10";
showed = true;
const element = document.querySelector("#exitDetect")
element.style.visibility = "visible"
element.style.opacity = "1"
element.style.transform = "scale(1)"
element.style.transition = "0.4s, opacity 0.4s"
}
const hide = () => {
const element = document.querySelector("#exitDetect")
element.style.visibility = "hidden"
element.style.opacity = "0"
element.style.transform = "scale(0.5)"
element.style.transition = "0.2s, opacity 0.2s, visibility 0s 0.2s"
}
const exit = e => {
hide()
}
document.addEventListener('mouseout', e => {
if (!e.toElement && !e.relatedTarget) {
show();
}
});
document.addEventListener("DOMContentLoaded", () => {
document.onkeydown = event => {
event = event || window.event
if (event.keyCode === 27) {
hide()
}
}
})
document.addEventListener("DOMContentLoaded", () => {
document.querySelector('#popUpCloser').addEventListener('click', exit);
})
</script>
<div id="exitDetect">
<div id="popUpCloser" style="display: block; cursor:pointer;">click here to close me</div>
</div>
var url = window.location.href.toLowerCase();
console.log(url);
var url2 = window.location.pathname.toLowerCase();
console.log(url2);
var menuTimeOutId = null;
var menuTimer = 300;
$j('.category-menu-title-sticky').on({
//mouse enter condition
mouseenter: function () {
if (menuTimeOutId == null) {
$j(menuDiv).show();
} else {
clearTimeout(menuTimeOutId);
menuTimeOutId = null;
}
// mouse leave condition
},mouseleave: function () {
if (menuTimeOutId != null) {
clearTimeout(menuTimeOutId);
menuTimeOutId = null;
}
menuTimeOutId = setTimeout(function () {
$j(menuDiv).hide();
menuTimeOutId = null;
}, menuTimer)
}
});
//merge 2 on condtion into 1 array condtion
//on({mouseenter,mouseleave})
//this a how to console json obj
console.log( JSON.stringify(jsonObject, null, " ") );
function mobilehead(){
$jw(".menu-mobile").click(function(){
$jw('.menu-mobile-container').animate({
left: '0'
}, 400, 'easeOutBack');
$jw('body').addClass("noscroll");
});
$jw(".closer-mobile-menu").click(function(){
//$("#navigation li a").removeClass("open");
$jw('.menu-mobile-container').animate({
left: '-100%'
}, 400, 'easeOutQuint');
$jw('body').removeClass("noscroll");
});
}
/** menggunakan jquery easing
http://gsgd.co.uk/sandbox/jquery/easing/
https://matthewlein.com/experiments/easing.html
**/
//Move some block div to other div using jquery and javascript
function move(){
$j(".NodesToMove").detach().appendTo('.DestinationContainerNode');
}
move();
const puppeteer = require('puppeteer');
const fs = require('fs');
async function run() {
const browser = await puppeteer.launch({
headless: false
});
const page = await browser.newPage();
await page.setViewport({ width: 1200, height: 1200 });
await page.goto('https://www.google.com/search?q=.net+core&rlz=1C1GGRV_enUS785US785&oq=.net+core&aqs=chrome..69i57j69i60l3j69i65j69i60.999j0j7&sourceid=chrome&ie=UTF-8');
//get image href
const IMAGE_SELECTOR = '#tsf > div:nth-child(2) > div > div.logo > a > img';
let imageHref = await page.evaluate((sel) => {
return document.querySelector(sel).getAttribute('src').replace('/', '');
}, IMAGE_SELECTOR);
console.log("https://www.google.com/" + imageHref);
var viewSource = await page.goto("https://www.google.com/" + imageHref);
fs.writeFile(".googles-20th-birthday-us-5142672481189888-s.png", await viewSource.buffer(), function (err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
});
browser.close();
}
run();
//make sticky DIV
function sticky_relocate() {
var window_top = $(window).scrollTop(); //scroll position global
var div_top = $('#sticky-anchor').offset().top; //boundary from div in content
if (window_top > div_top) {
$('.toolbar-sticky').addClass('stick-up');
$('#sticky-anchor').height(0);
} else {
$('.toolbar-sticky').removeClass('stick-up');
$('#sticky-anchor').height(0);
}
}
$(function() {
$(window).scroll(sticky_relocate);
sticky_relocate();
});
/**
css haru ada class
.stick-up {
position: fixed;
top: 0;
z-index: 10000;
display: block;
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment