Repository: argyleink/blingblingjs Branch: master Commit: 1c118df2f91f Files: 11 Total size: 16.6 KB Directory structure: gitextract_0aw0chu9/ ├── .gitattributes ├── .github/ │ └── workflows/ │ └── main.yml ├── .gitignore ├── LICENSE ├── README.md ├── dist/ │ └── index.js ├── index.html ├── package.json ├── playground.js └── src/ ├── index.js └── index.test.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitattributes ================================================ # Auto detect text files and perform LF normalization * text=auto ================================================ FILE: .github/workflows/main.yml ================================================ name: Ava Tests on: [push, pull_request] jobs: build: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@master - name: Install uses: ianwalter/playwright-container@v3.0.0 - name: Install NPM Deps uses: ianwalter/playwright-container@v3.0.0 with: args: npm i - name: Test uses: ianwalter/playwright-container@v3.0.0 with: args: npm test ================================================ FILE: .gitignore ================================================ node_modules/ ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2018 Adam Argyle Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # BlingBlingJS

Build Status Total Downloads Latest Release License

> like [bling.js](https://gist.github.com/paulirish/12fb951a8b893a454b32), but more bling
###### Getting Started ### Installation ```bash npm i blingblingjs ``` ### Importing ```js // import the blingbling y'all import $ from 'blingblingjs' // es6 module const $ = require('blingblingjs') // commonjs // or from Pika CDN! https://cdn.pika.dev/blingblingjs/v2 ``` ### [Bookmarklet](https://github.com/argyleink/blingblingjs/issues/42) ```js javascript: fetch('https://cdn.jsdelivr.net/npm/blingblingjs@latest/dist/index.min.js').then((x) => x.text()).then((x) => { eval(x); $ = $.default; console.log("💲 BlingBlingJS ready 💲"); }); ```
###### Syntax ### Quick Overview ```js $() // select nodes in document or pass nodes in $().on // add multiple event listeners to multiple nodes $().off // remove multiple event listeners from multiple nodes $().attr // CRUD attributes on nodes $().map // use native array methods ```
### Queries ```js // get nodes from the document const btns = $('button') // blingbling always returns an array const [first_btn] = $('button[primary]') // destructure shortcut for 1st/only match const btn_spans = $('span', btns) // provide a query context by passing a 2nd param of node/nodes // cover DOM nodes in bling const [sugared_single] = $(document.querySelector('button')) const sugared_buttons = $(document.querySelectorAll('button')) ```
### Array Methods ```js $('button').forEach(...) $('button').map(...) const btns = $('button') btns.filter(...) btns.reduce(...) btns.flatMap(...) ... ```
### Events ```js // single events first_btn.on('click', ({target}) => console.log(target)) $('button[primary]').on('click', e => console.log(e)) // single events with options first_btn.on('click', ({target}) => console.log(target), {once: true}) $('button[primary]').on('click', e => console.log(e), true) // useCapture // multiple events $('h1').on('click touchend', ({target}) => console.log(target)) // remove events const log_event = e => console.warn(e) // must have a reference to the original function main_btn.on('contextmenu', log_event) main_btn.off('contextmenu', log_event) ```
### Attributes ```js // set an attribute $('button.rad').attr('rad', true) // set multiple attributes const [rad_btn] = $('button.rad') rad_btn.attr({ test: 'foo', hi: 'bye', }) // get an attribute rad_btn.attr('rad') // "true" rad_btn.attr('hi') // "bye" // get multiple attributes $('button').map(btn => ({ tests: btn.attr('tests'), hi: btn.attr('hi'), })) // remove an attribute rad_btn.attr('hi', null) // set to null to remove rad_btn.attr('hi') // attribute not found // remove multiple attributes btns.attr({ test: null, hi: null, }) ```
### Convenience ```js import {rIC, rAF} from 'blingblingjs' // requestAnimationFrame rAF(_ => { // animation tick }) // requestIdleCallback rIC(_ => { // good time to compute }) ```

###### What for? **Developer ergonomics!** If you agree with any of the following, you may appreciate this micro library: * Love vanilla js, want to keep your code close to it * Chaining is fun, Arrays are fun, essentially a functional programming fan * Hate typing `document.querySelector` over.. and over.. * Hate typing `addEventListener` over.. and over.. * Really wish `document.querySelectorAll` had array methods on it.. * Confused that there is no `node.setAttributes({...})` or even better `nodeList.setAttributes({...})` * Liked jQuery selector syntax ###### Why BlingBling? - Minimal at 0.6kb (636 bytes) - BlingBling supports ES6 module importing and common module loading - Supports chaining - Worth it's weight (should save more characters than it loads) - Only enhances the nodes you query with it - ES6 version of popular [bling.js](https://gist.github.com/paulirish/12fb951a8b893a454b32) by Paul Irish - [Tested](https://github.com/argyleink/blingblingjs/blob/master/src/index.test.js) ================================================ FILE: dist/index.js ================================================ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = global || self, factory(global.$ = {})); }(this, function (exports) { 'use strict'; const sugar = { on: function(names, fn, options) { names .split(' ') .forEach(name => this.addEventListener(name, fn, options)); return this }, off: function(names, fn, options) { names .split(' ') .forEach(name => this.removeEventListener(name, fn, options)); return this }, attr: function(attr, val) { if (val === undefined) return this.getAttribute(attr) val == null ? this.removeAttribute(attr) : this.setAttribute(attr, val); return this } }; const rAF = typeof requestAnimationFrame !== 'undefined' && requestAnimationFrame; const rIC = typeof requestIdleCallback !== 'undefined' && requestIdleCallback; function $(query, $context = document) { let $nodes = query instanceof NodeList || Array.isArray(query) ? query : query instanceof HTMLElement || query instanceof SVGElement ? [query] : $context.querySelectorAll(query); if (!$nodes.length) $nodes = []; return Object.assign( Array.from($nodes).map($el => Object.assign($el, sugar)), { on: function(names, fn, options) { this.forEach($el => $el.on(names, fn, options)); return this }, off: function(names, fn, options) { this.forEach($el => $el.off(names, fn, options)); return this }, attr: function(attrs, val) { if (typeof attrs === 'string' && val === undefined) return this[0].attr(attrs) else if (typeof attrs === 'object') this.forEach($el => Object.entries(attrs) .forEach(([key, val]) => $el.attr(key, val))); else if (typeof attrs == 'string') this.forEach($el => $el.attr(attrs, val)); return this } } ) } exports.default = $; exports.rAF = rAF; exports.rIC = rIC; Object.defineProperty(exports, '__esModule', { value: true }); })); ================================================ FILE: index.html ================================================ BlingBling ================================================ FILE: package.json ================================================ { "name": "blingblingjs", "version": "2.3.0", "description": "like bling.js, but more bling", "repository": { "type": "git", "url": "https://github.com/argyleink/blingblingjs.git" }, "main": "dist/index.js", "module": "src/index.js", "scripts": { "test": "npm run build && ava -v", "build": "rollup src/index.js --format umd --name \"$\" --file dist/index.js" }, "author": "argyleink", "keywords": [ "javascript", "utility", "jquery-like", "es6" ], "license": "MIT", "bugs": { "url": "https://github.com/argyleink/blingblingjs/issues" }, "devDependencies": { "ava": "^1.4.1", "browser-env": "^3.2.6", "rollup": "^1.9.0" } } ================================================ FILE: playground.js ================================================ import $, {rAF, rIC} from './src/index.js' let test = document.querySelectorAll('button') console.log($(test[0]).on) rAF(_ => console.log('rAF')) rIC(_ => console.log('rIC')) // ;(function repeatOften() { // console.log('requestAnimationFrame') // rAF(repeatOften); // })(); ================================================ FILE: src/index.js ================================================ const sugar = { on: function(names, fn, options) { names .split(' ') .forEach(name => this.addEventListener(name, fn, options)) return this }, off: function(names, fn, options) { names .split(' ') .forEach(name => this.removeEventListener(name, fn, options)) return this }, attr: function(attr, val) { if (val === undefined) return this.getAttribute(attr) val == null ? this.removeAttribute(attr) : this.setAttribute(attr, val) return this } } export const rAF = typeof requestAnimationFrame !== 'undefined' && requestAnimationFrame export const rIC = typeof requestIdleCallback !== 'undefined' && requestIdleCallback export default function $(query, $context = document) { let $nodes = query instanceof NodeList || Array.isArray(query) ? query : query instanceof HTMLElement || query instanceof SVGElement ? [query] : $context.querySelectorAll(query) if (!$nodes.length) $nodes = [] return Object.assign( Array.from($nodes).map($el => Object.assign($el, sugar)), { on: function(names, fn, options) { this.forEach($el => $el.on(names, fn, options)) return this }, off: function(names, fn, options) { this.forEach($el => $el.off(names, fn, options)) return this }, attr: function(attrs, val) { if (typeof attrs === 'string' && val === undefined) return this[0].attr(attrs) else if (typeof attrs === 'object') this.forEach($el => Object.entries(attrs) .forEach(([key, val]) => $el.attr(key, val))) else if (typeof attrs == 'string') this.forEach($el => $el.attr(attrs, val)) return this } } ) } ================================================ FILE: src/index.test.js ================================================ import test from 'ava' import browserEnv from 'browser-env' import $, {rAF, rIC} from '../dist/index.js' browserEnv() test.afterEach.always(t => { document.body.innerHTML = '' }) test('$("div")', t => { const div = document.createElement('div') document.body.appendChild(div) t.is($('div')[0], div) t.pass() }) test('$(node)', t => { const div = document.createElement('div') t.truthy($(div).on) t.truthy($(div).attr) t.pass() }) test('$("bad_query")', t => { t.truthy($('bad').length == 0) t.pass() }) test('$("div", parent)', t => { const div = document.createElement('div') const p = document.createElement('p') div.appendChild(p) div.appendChild(p) t.is($('p', div)[0], p) t.pass() }) test('$("div") multiple', t => { const div = document.createElement('div') const len = 3 for (var i = 0; i < len; i++) document.body.appendChild(div) t.is($('div').length, len - 1) t.pass() }) test('$(nodes)', t => { const div = document.createElement('div') const len = 3 for (var i = 0; i < len; i++) document.body.appendChild(div) const nodes = document.querySelectorAll('div') t.truthy($(nodes).on) t.truthy($(nodes).attr) t.pass() }) test('$("div", parent) multiple', t => { const div = document.createElement('div') const p = document.createElement('p') const len = 3 for (var i = 0; i < len; i++) div.appendChild(p) t.is($('p', div).length, div.querySelectorAll('p').length) t.pass() }) test('$("p").map(el => ...)', t => { const div = document.createElement('div') const p = document.createElement('p') const len = 3 for (var i = 0; i < len; i++) document.body.appendChild(p) t.is($('p').map, Array.prototype.map) t.is($('p').filter, Array.prototype.filter) t.is($('p').reduce, Array.prototype.reduce) t.pass() }) test('$("button").attr({...})', t => { const btn = document.createElement('button') document.body.appendChild(btn) t.falsy(btn.hasAttribute('foo')) $('button').attr({ foo: 'bar' }) t.truthy(btn.hasAttribute('foo')) t.pass() }) test('$("button").attr({...}) multiple', t => { const btn = document.createElement('button') document.body.appendChild(btn) document.body.appendChild(btn) t.falsy(btn.hasAttribute('foo')) $('button').attr({ foo: 'bar' }) t.truthy(btn.hasAttribute('foo')) t.pass() }) test('$("button").attr("foo", falsy_value)', t => { const btn = document.createElement('button') document.body.appendChild(btn) t.falsy(btn.hasAttribute('foo')) const $btn = $('button') const value = 0 $btn.attr('foo', value) t.is($btn.attr('foo'), value.toString()) t.pass() }) test.cb('$("button").on("click", e => ...)', t => { const btn = document.createElement('button') btn.classList.add('test') document.body.appendChild(btn) $('.test').on('click', e => t.end()) btn.click() }) test('$("button").on("click ...", e => ...) multiple', t => { t.plan(2) const btn = document.createElement('button') $(btn).on('click dblclick', e => t.pass()) btn.click() btn.dispatchEvent(new window.MouseEvent('dblclick', { bubbles: true })) }) test.cb('$(node).on("click", e => ...)', t => { const btn = document.createElement('button') $(btn).on('click', e => t.end()) btn.click() }) test.cb('$("button").on("click", e => ...) multiple', t => { const btn = document.createElement('button') btn.classList.add('test') document.body.appendChild(btn) document.body.appendChild(btn) $('.test').on('click', e => t.end()) btn.click() }) test('$(nodes).on("click ...", e => ...) multiple', t => { t.plan(2) const btn = document.createElement('button') document.body.appendChild(btn) document.body.appendChild(btn) const list = document.querySelectorAll('button') $(list).on('click dblclick', e => t.pass()) btn.click() btn.dispatchEvent(new window.MouseEvent('dblclick', { bubbles: true })) }) test.cb('$(node).on("click", e => ...) multiple', t => { const btn = document.createElement('button') document.body.appendChild(btn) document.body.appendChild(btn) const list = document.querySelectorAll('button') $(list).on('click', e => t.end()) btn.click() }) test.cb('$("button").on("click", e => ..., { once:true })', t => { t.plan(3) const btn = document.createElement('button') btn.classList.add('test') document.body.appendChild(btn) let eventCount = 0 $('.test').on('click', e => { eventCount++ t.end() }, { once:true }) t.is(eventCount, 0) btn.click() t.is(eventCount, 1) btn.click() t.is(eventCount, 1) }) test('$("button").on("click ...", e => ..., { once:true }) multiple', t => { t.plan(5) const btn = document.createElement('button') let eventCount = 0 $(btn).on('click dblclick', e => { eventCount++ t.end() }, { once:true }) t.is(eventCount, 0) btn.click() t.is(eventCount, 1) btn.dispatchEvent(new window.MouseEvent('dblclick', { bubbles: true })) t.is(eventCount, 2) btn.click() t.is(eventCount, 2) btn.dispatchEvent(new window.MouseEvent('dblclick', { bubbles: true })) t.is(eventCount, 2) }) test.serial('rAF', async (t) => { rAF ? rAF(_ => t.pass()) : t.pass() }) test.serial('rIC', async (t) => { rIC ? rIC(_ => t.pass()) : t.pass() })