Jump to Categories

.Cheatsheet

Is not undefined

// to check if a variable is declared and is not undefined
if (typeof yourvar !== 'undefined')

// Does not execute if yourvar is `undefined`
if (yourvar === null)

// If know the variable exists, and want to check whether there's any value stored in it
if (yourvar !== undefined)

// If is true, or false
if (yourvar)
if (!yourvar)

Mobile swipe


document.addEventListener('touchstart', handleTouchStart, false);        
document.addEventListener('touchmove', handleTouchMove, false);

var xDown = null;                                                        
var yDown = null;                                                        

function handleTouchStart(evt) {                                         
    xDown = evt.touches[0].clientX;                                      
    yDown = evt.touches[0].clientY;                                      
};                                                

function handleTouchMove(evt) {
    if ( ! xDown || ! yDown ) {
        return;
    }

    var xUp = evt.touches[0].clientX;                                    
    var yUp = evt.touches[0].clientY;

    var xDiff = xDown - xUp;
    var yDiff = yDown - yUp;

    if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {/*most significant*/
        if ( xDiff > 0 ) {
            /* left swipe */ 
        } else {
            /* right swipe */
        }                       
    } else {
        if ( yDiff > 0 ) {
            /* up swipe */ 
        } else { 
            /* down swipe */
        }                                                                 
    }
    /* reset values */
    xDown = null;
    yDown = null;                                             
};

Stackoverflow - givanse

Get Day

var d = new Date();
console.log(d);

var c = new Date('1964-03-30T16:43:40.723Z');
var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
console.log(days[c.getDay()]);

Get CSS values in JS

Inline styles

<div class="el" style="font-size: 2em; color: red;">1234</div>
const element = document.querySelector('.element')

const fontSize = element.style.fontSize
console.log(fontSize) // 2em

const color = element.style.color
console.log(color) // red

From a stylesheet

const style = getComputedStyle(element)

getComputedStyle is read-only. You cannot set a CSS value with getComputedStyle unlike inline styles

From pseudo elements

.element::before { content: "Before pseudo element"; }
pseudoElementStyle = getComputedStyle(element, '::before')