Skip to content

Instantly share code, notes, and snippets.

@crazyyy
Last active October 2, 2021 16:27
Show Gist options
  • Save crazyyy/f3b25adac07f07dfd0e89b18083a96a2 to your computer and use it in GitHub Desktop.
Save crazyyy/f3b25adac07f07dfd0e89b18083a96a2 to your computer and use it in GitHub Desktop.
🀷 #js #javascript Favorit Snipps
{
"camelcase": true,
"indent": 2,
"undef": true,
"quotmark": false,
"maxlen": 120,
"trailing": true,
"curly": true,
"strict": false,
"browser": true,
"devel": true,
"jquery": true,
"esversion": 9,
"node": true
}

JS snippents

Color console.log

console.log('%c Auth ', 
            'color: white; background-color: #2274A5', 
            'Login page rendered');
console.log('%c GraphQL ', 
            'color: white; background-color: #95B46A', 
            'Get user details');
console.log('%c Error ', 
            'color: white; background-color: #D33F49', 
            'Error getting user details');

input events

  input.addEventListener('focus', funcElementFocusIn, true);
  input.addEventListener('blur', funcElementFocusOut, true);
  input.addEventListener("keypress", funcElementKeyPress, false);

  funcElementFocusIn(event){
    const target = event.target
  }

jQuery Document ready

jQuery('document').ready(function ($) {
  $('.cart-button').click(function () {
    $('.product-cart-modal').toggleClass('active')
  })
})

Check current ViewPort

const ViewPort = {
    width: Math.max(document.documentElement.clientWidth, window.innerWidth || 0),
    init: function() {
        this.update();
        window.onresize = function() {
            ViewPort.update()
        }
    },
    update: function() {
        console.log(`prev / next = ${this.width} / ${Math.max(document.documentElement.clientWidth, window.innerWidth || 0)}`)
        this.width = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
    },
    isSizeXS: function() {
        return (this.width >= 320) && (this.width <= 575);
    },
    isSizeSM: function() {
        return (this.width >= 576) && (this.width <= 767);
    },
    isSizeMD: function() {
        return (this.width >= 768) && (this.width <= 991);
    },
    isSizeLG: function() {
        return (this.width >= 992) && (this.width <= 1199);
    },
    isSizeXL: function() {
        return (this.width >= 1200);
    },
    isMobile: function() {
        return (this.width <= 767);
    },
    isDesktop: function() {
        return (this.width >= 992);
    },
    is: function(taskname) {
        let statement = this[taskname]();
        if (statement) {
            console.log(`%c ${taskname} => %ctrue`, "font-size:12px; color: white", "font-size:12px; color: green");
        } else {
            console.log(`%c ${taskname} => %cfalse`, "font-size:12px; color: gray", "font-size:12px; color: red");
        }
    },
    showAll: function() {
        ['isMobile', 'isDesktop', 'isSizeXS', 'isSizeSM', 'isSizeMD', 'isSizeLG', 'isSizeXL'].map((taskname) => {
            this.is(taskname)
        })
    }
}

ViewPort.init();
ViewPort.showAll();
ViewPort.is('isMobile');
ViewPort.is('isSizeXS');
if (ViewPort.isSizeXL() === true) { /*...*/ }

create element

  // source from https://github.com/jelastic/jelastic-widget/blob/master/assets/js/jlcwidget.js
  // main function
  function CreateElement(tagName, attrs, text) {
    const element = document.createElement(tagName);
    if (attrs) {
      for (let attribute in attrs) {
        let value = attrs[attribute];
        if (attribute === 'className') {
          attribute = 'class';
        }
        let element_attribute = document.createAttribute(attribute);
        element_attribute.value = value;
        element.setAttributeNode(element_attribute);
      }
    }
    if (text) {
      let element_content = document.createTextNode(text);
      element.appendChild(element_content);
    }
    return element;
  }

  // create simple element with class 
  const elNew = CreateElement('div', {
    className: 'element-class'
  });

  // appent element inside another 
  const wrapper = document.querySelector('.wrapper');
  wrapper.appendChild(elNew);

  // create element with content, button for example 
  const elButton = CreateElement('button', {
    className: 'button-class'
  }, 'Button Text');
  wrapper.appendChild(elButton);

  // create element with attributes
  const elInput = CreateElement('input', {
    className: 'input-class',
    placeholder: '[email protected]',
    type: 'email',
    required: 'true'
  });
  wrapper.appendChild(elInput);

Debug snippets

Console: Поиск ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚Ρ‡ΠΈΠΊΠΎΠ² событий, привязанных ΠΊ элСмСнту

// Π’ процСссС ΠΎΡ‚Π»Π°Π΄ΠΊΠΈ ΠΌΠΎΠΆΠ΅Ρ‚ ΠΏΠΎΠ½Π°Π΄ΠΎΠ±ΠΈΡ‚ΡŒΡΡ Π½Π°ΠΉΡ‚ΠΈ ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚Ρ‡ΠΈΠΊΠΈ событий, привязанныС ΠΊ элСмСнтам. Π‘ ΠΏΠΎΠΌΠΎΡ‰ΡŒΡŽ консоли ΡΠ΄Π΅Π»Π°Ρ‚ΡŒ это ΠΎΡ‡Π΅Π½ΡŒ просто. Достаточно Π²ΠΎΡΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚ΡŒΡΡ Ρ‚Π°ΠΊΠΎΠΉ ΠΊΠΎΠΌΠ°Π½Π΄ΠΎΠΉ:
getEventListeners($('selector'))

// Π’ Ρ€Π΅Π·ΡƒΠ»ΡŒΡ‚Π°Ρ‚Π΅ Π΅Ρ‘ выполнСния Π±ΡƒΠ΄Π΅Ρ‚ Π²Ρ‹Π΄Π°Π½ массив ΠΎΠ±ΡŠΠ΅ΠΊΡ‚ΠΎΠ², содСрТащий список событий, Π½Π° ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Π΅ ΠΌΠΎΠΆΠ΅Ρ‚ Ρ€Π΅Π°Π³ΠΈΡ€ΠΎΠ²Π°Ρ‚ΡŒ элСмСнт.
// Для Ρ‚ΠΎΠ³ΠΎ, Ρ‡Ρ‚ΠΎΠ±Ρ‹ Π½Π°ΠΉΡ‚ΠΈ ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚Ρ‡ΠΈΠΊ для ΠΊΠΎΠ½ΠΊΡ€Π΅Ρ‚Π½ΠΎΠ³ΠΎ события, ΠΌΠΎΠΆΠ½ΠΎ ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚ΡŒ Ρ‚Π°ΠΊΡƒΡŽ ΠΊΠΎΠ½ΡΡ‚Ρ€ΡƒΠΊΡ†ΠΈΡŽ:
getEventListeners($('selector')).eventName[0].listener

// Π­Ρ‚Π° ΠΊΠΎΠΌΠ°Π½Π΄Π° Π²Ρ‹Π²Π΅Π΄Π΅Ρ‚ ΠΊΠΎΠ΄ Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠΈ-ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚Ρ‡ΠΈΠΊΠ° события. Π—Π΄Π΅ΡΡŒ eventName[0] – это массив, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹ΠΉ содСрТит всС события ΠΊΠΎΠ½ΠΊΡ€Π΅Ρ‚Π½ΠΎΠ³ΠΎ Ρ‚ΠΈΠΏΠ°. НапримСр, Π½Π° ΠΏΡ€Π°ΠΊΡ‚ΠΈΠΊΠ΅ это ΠΌΠΎΠΆΠ΅Ρ‚ Π²Ρ‹Π³Π»ΡΠ΄Π΅Ρ‚ΡŒ Ρ‚Π°ΠΊ:
getEventListeners($('#firstName')).click[0].listener

// Π’ Ρ€Π΅Π·ΡƒΠ»ΡŒΡ‚Π°Ρ‚Π΅ ΠΌΡ‹ ΠΏΠΎΠ»ΡƒΡ‡ΠΈΠΌ ΠΊΠΎΠ΄ Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠΈ, связанной с событиСм click элСмСнта с ΠΈΠ΄Π΅Π½Ρ‚ΠΈΡ„ΠΈΠΊΠ°Ρ‚ΠΎΡ€ΠΎΠΌ firstName.

Console: ΠœΠΎΠ½ΠΈΡ‚ΠΎΡ€ΠΈΠ½Π³ событий

// Если Π²Ρ‹ Ρ…ΠΎΡ‚ΠΈΡ‚Π΅ ΠΏΠΎΠ½Π°Π±Π»ΡŽΠ΄Π°Ρ‚ΡŒ Π·Π° Π²ΠΎΠ·Π½ΠΈΠΊΠ½ΠΎΠ²Π΅Π½ΠΈΠ΅ΠΌ событий, привязанных ΠΊ ΠΊΠΎΠ½ΠΊΡ€Π΅Ρ‚Π½ΠΎΠΌΡƒ элСмСнту DOM, консоль Π² этом ΠΏΠΎΠΌΠΎΠΆΠ΅Ρ‚. Π’ΠΎΡ‚ нСсколько ΠΊΠΎΠΌΠ°Π½Π΄, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Π΅ ΠΌΠΎΠΆΠ½ΠΎ ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚ΡŒ для ΠΌΠΎΠ½ΠΈΡ‚ΠΎΡ€ΠΈΠ½Π³Π° событий.
monitorEvents($('selector'))

// Команда monitorEvents($(β€˜selector’)) позволяСт ΠΎΡ€Π³Π°Π½ΠΈΠ·ΠΎΠ²Π°Ρ‚ΡŒ ΠΌΠΎΠ½ΠΈΡ‚ΠΎΡ€ΠΈΠ½Π³ всСх событий, связанных с элСмСнтом, ΠΊΠΎΡ‚ΠΎΡ€ΠΎΠΌΡƒ соотвСтствуСт сСлСктор. ΠŸΡ€ΠΈ Π²ΠΎΠ·Π½ΠΈΠΊΠ½ΠΎΠ²Π΅Π½ΠΈΠΈ события дСлаСтся запись Π² консоли. НапримСр, ΠΊΠΎΠΌΠ°Π½Π΄Π° monitorEvents($(β€˜#firstName’)) ΠΏΠΎΠ·Π²ΠΎΠ»ΠΈΡ‚ Π»ΠΎΠ³ΠΈΡ€ΠΎΠ²Π°Ρ‚ΡŒ всС события, связанныС с элСмСнтом, ΠΈΠ΄Π΅Π½Ρ‚ΠΈΡ„ΠΈΠΊΠ°Ρ‚ΠΎΡ€ ΠΊΠΎΡ‚ΠΎΡ€ΠΎΠ³ΠΎ – firstName.
// Команда monitorEvents($(β€˜selector’),’eventName’) ΠΏΠΎΡ…ΠΎΠΆΠ° Π½Π° ΠΏΡ€Π΅Π΄Ρ‹Π΄ΡƒΡ‰ΡƒΡŽ, Π½ΠΎ ΠΎΠ½Π° Π½Π°Ρ†Π΅Π»Π΅Π½Π° Π½Π° ΠΊΠΎΠ½ΠΊΡ€Π΅Ρ‚Π½ΠΎΠ΅ событиС. Π—Π΄Π΅ΡΡŒ, ΠΏΠΎΠΌΠΈΠΌΠΎ сСлСктора элСмСнта, Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠΈ пСрСдаётся ΠΈ имя события. Вакая ΠΊΠΎΠΌΠ°Π½Π΄Π° ΠΏΠΎΠ·Π²ΠΎΠ»ΠΈΡ‚ вывСсти Π² консоль Π΄Π°Π½Π½Ρ‹Π΅ ΠΎ Π²ΠΎΠ·Π½ΠΈΠΊΠ½ΠΎΠ²Π΅Π½ΠΈΠΈ ΠΎΠ΄Π½ΠΎΠ³ΠΎ события. НапримСр, ΠΊΠΎΠΌΠ°Π½Π΄Π° monitorEvents($(β€˜#firstName’),’click’) Π²Ρ‹Π²Π΅Π΄Π΅Ρ‚ свСдСния Ρ‚ΠΎΠ»ΡŒΠΊΠΎ ΠΏΠΎ ΡΠΎΠ±Ρ‹Ρ‚ΠΈΡŽ click элСмСнта с ΠΈΠ΄Π΅Π½Ρ‚ΠΈΡ„ΠΈΠΊΠ°Ρ‚ΠΎΡ€ΠΎΠΌ firstName.
// Команда monitorEvents($(β€˜selector’),[β€˜eventName1’,’eventName3',….]) позволяСт Π½Π°Π±Π»ΡŽΠ΄Π°Ρ‚ΡŒ Π·Π° нСсколькими Π²Ρ‹Π±Ρ€Π°Π½Π½Ρ‹ΠΌΠΈ событиями. Π—Π΄Π΅ΡΡŒ Π² Ρ„ΡƒΠ½ΠΊΡ†ΠΈΡŽ пСрСдаётся строковой массив, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹ΠΉ содСрТит ΠΈΠΌΠ΅Π½Π° событий. НапримСр, такая ΠΊΠΎΠΌΠ°Π½Π΄Π°: monitorEvents($(β€˜#firstName’),[β€˜click’,’focus’]) Π±ΡƒΠ΄Π΅Ρ‚ Π²Ρ‹Π²ΠΎΠ΄ΠΈΡ‚ΡŒ Π² консоль свСдСния ΠΎ событиях click ΠΈ focus для элСмСнта с ΠΈΠ΄Π΅Π½Ρ‚ΠΈΡ„ΠΈΠΊΠ°Ρ‚ΠΎΡ€ΠΎΠΌ firstName.
// Команда unmonitorEvents($(β€˜selector’)) позволяСт ΠΏΡ€Π΅ΠΊΡ€Π°Ρ‚ΠΈΡ‚ΡŒ ΠΌΠΎΠ½ΠΈΡ‚ΠΎΡ€ΠΈΠ½Π³ ΠΈ Π»ΠΎΠ³ΠΈΡ€ΠΎΠ²Π°Π½ΠΈΠ΅ событий Π² консоли.
unmonitorEvents($('selector'))

Console: Π’Ρ‹Π²ΠΎΠ΄ списка свойств элСмСнта

// Если Π½Π°Π΄ΠΎ ΠΏΡ€ΠΎΡΠΌΠΎΡ‚Ρ€Π΅Ρ‚ΡŒ список свойств элСмСнта, консоль ΠΏΠΎΠΌΠΎΠΆΠ΅Ρ‚ ΠΈ Π² этом. Π—Π΄Π΅ΡΡŒ ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΡƒΠ΅Ρ‚ΡΡ такая ΠΊΠΎΠΌΠ°Π½Π΄Π°:
dir($('selector'))
//  Она Π²ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅Ρ‚ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚, содСрТащий свойства, связанныС с Π·Π°Π΄Π°Π½Π½Ρ‹ΠΌ элСмСнтом DOM. Как ΠΈ Π² ΠΏΡ€ΠΎΡ‡ΠΈΡ… ΠΏΠΎΠ΄ΠΎΠ±Π½Ρ‹Ρ… случаях, содСрТимоС этого ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Π° ΠΌΠΎΠΆΠ½ΠΎ ΠΈΡΡΠ»Π΅Π΄ΠΎΠ²Π°Ρ‚ΡŒ, просматривая Π΅Π³ΠΎ Π΄Ρ€Π΅Π²ΠΎΠ²ΠΈΠ΄Π½ΡƒΡŽ структуру.

Check if element in page

  const eForm = document.getElementById('form');

  if (typeof(eForm) != 'undefined' && eForm != null) {
    // element on page 
  } else {
    // nothing 
    // return false 
  }
  const errBlock = document.getElementById('error');
  if (typeof errBlock == 'undefined' && errBlock == null) {
    // form does not exist
    return false;
  }

load additional scripts in webpack

vendor.js
try {
    window.$ = window.jQuery = $ = require("jquery");
    window.Popper = require("popper.js");
    require("bootstrap");
    require("../../node_modules/jquery-validation/dist/jquery.validate.js");
    require("../../node_modules/jquery-validation/dist/additional-methods.js");
} catch (e) {
    console.log(e);
}
webpack.mix.js
const mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.autoload({
        jquery: ['window.$', 'window.jQuery'],
        'popper.js/dist/umd/popper.js': ['Popper']
    })
    .js('resources/js/app.js', 'public/js')
    .js('resources/js/vendor.js', 'public/js')
    .sass('resources/sass/app.scss', 'public/css')
    .options({
        processCssUrls: false
    })
    .version();

if (process.env.MIX_BROWSER_SYNC_DOMAIN) {
    mix.browserSync('traffic-school.local');
}


if (!mix.inProduction()) {
    mix.sourceMaps()
        .webpackConfig({
            devtool: 'source-map'
        });
}```

Query selectors

const myNodeList = document.querySelectorAll('.my-selector');`

ES6 +

const nodeArray = Array(...nodeList);

ES5

const nodeArray = Array.from(myNodeList);

const nodeArray = Array.from(document.querySelectorAll('[data-time]'));

ALT 1

Array.from(myNodeList).forEach(function(el) {
  console.log(el);
});

ALT 2

for (var el of myNodeList) {
  el.classList.add('active'); // or some other action
}

ALT 3

[...myNodeList].forEach((el) => {
  console.log(el);
});
/**
 * Define the chunk method in the prototype of an array
 * that returns an array with arrays of the given size.
 *
 * @param chunkSize {Integer} Size of every group
 */

Object.defineProperty(Array.prototype, 'chunk', {
  value: function value(chunkSize) {
    const that = this;
    return Array(Math.ceil(that.length / chunkSize)).fill().map((_, i) => that.slice(i * chunkSize, i * chunkSize + chunkSize));
  },
});

usage

const data = [1, 2, 3, 4, 5, 6, 7, 8];
const chunks = data.chunk(3);
console.log(chunks); // [[1, 2, 3], [4, 5, 6], [7, 8]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment