GithubHelp home page GithubHelp logo

argyleink / blingblingjs Goto Github PK

View Code? Open in Web Editor NEW
223.0 5.0 15.0 442 KB

๐Ÿ’ฒ Micro-library of shorthands for DOM selection, events, and attribute manipulation

License: MIT License

JavaScript 93.36% HTML 6.64%
javascript es6 commonjs dom-manipulation jquery-like tdd utility-function

blingblingjs's Introduction

BlingBlingJS

Build Status Total Downloads Latest Release License

like bling.js, but more bling


Getting Started

Installation

npm i blingblingjs

Importing

// import the blingbling y'all
import $ from 'blingblingjs'                // es6 module
const $ = require('blingblingjs')           // commonjs

// or from Pika CDN! https://cdn.pika.dev/blingblingjs/v2
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

$()        // 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

// 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

$('button').forEach(...)
$('button').map(...)

const btns = $('button')
btns.filter(...)
btns.reduce(...)
btns.flatMap(...)
...

Events

// 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

// 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

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 by Paul Irish
  • Tested

blingblingjs's People

Contributors

argyleink avatar hchiam avatar markpalfreeman avatar robmaple avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

blingblingjs's Issues

Add `$().data` for handling `data-*`

I coded up a mockup of the idea here. While there is overlap with .attr() I think there could still be a place for it. especially when handling data that can't be coerced to a string.

$('div').attr('data-user', {
  fname: 'argyle',
  lname: 'ink'
});

$('div').attr('user') // "[object Object]"

// data-user="{"fname":"ginger","lname":"chew"}"
$('div').data('user', {
  fname: 'ginger',
  lname: 'chew'
});

$('div').data('user') // { fname: 'ginger', lname: 'chew' }

// Needing to set `data-` like this on an object is frustrating
$('div').attr({
  'data-fname': 'argyle',
  'data-lname': 'ink'
  'data-user-id': 1
});

// the `data-` is assumed and don't need to wrap the keys in quotes
// and converting camelCase to kebab-case is handled automatically
$('div').data({
  fname: 'ginger',
  lname: 'chew',
  userId: 2
})

The mockup handles set/get/delete, so accepting an object as the first argument like in .attr() isn't there yet.

pass "JQuery"-name as an parameter/options to give blingblingjs a "new name"

Hi,
some plugins are independent of the jquery name to be able to work, for example Bootstrap 4 or other plugins.

Is it perhaps possible to add the JQuery as an option to blingblingjs and make the other plugins which are dependent of JQuery to work? Of course I do know that those plugins are dependent of JQuery functions which perhaps may not be available in the current state of blingblingjs.

But this functionality would be pretty cool to have!

regards

Set window.$ = blingblingjs in UMD build

Excited to try out blingblingjs for quick prototyping without a build step. I dropped it into an HTML file via unpkg.com, and I was surprised that window.$ was undefined. Turns out that window.blingblingjs is what gets defined, so to use $ as seems to be the convention from the README, I have to do the following:

<!DOCTYPE html>
<script src="//unpkg.com/[email protected]/dist/index.js"></script>
<script>
  var $ = blingblingjs;
</script>

Proposal:

  1. Continue setting window.blingblingjs
  2. If window.$ is undefined, set it to point to blingblingjs

nodeList not iterable in older browsers causing error

I'm getting an error in Safari 9 (although presumably this applies to similarly old browsers) due to the use of the spread operator on line 37.

This issue appears after transpilation with Babel and seems to be due to nodeLists not being iterable in older browsers.

[...$nodes].map($el => Object.assign($el, sugar)),

A quick fix would be to wrap $nodes in Array.from(...) although I'm not sure at first glance if that would break anything.

Happy to submit a PR if that seems like a viable fix.

Is it possible to read a dynamic value from an input field?

I have an input field:

<input type="text" id="querytext" placeholder="some query words" value="some other words" />

I'm trying to read what is the present value of the input field. I tried this, but I only get the predefined value some other words:

import $ from './blingbling.js'
$('#querytext').on('keydown', e => querytext())

const querytext = function () {
  const [txt] = $(document.querySelector('input#querytext'))
  console.log(txt.attr('value'))
}

a bookmarklet for quick temporary use in the browser console with chrome keyboard shortcuts?

why

i can't always install blingblingjs or jQuery for certain projects, but i'd still like to avoid manually typing things like [...document.querySelectorAll('a')].map(x=>x.addEventListener( when i'm quickly debugging stuff in the devtools console. it's also a little wasteful to fetch all of jQuery when i usually only need to do a few things with selecting and .on.

Using a bookmarklet seems to address this nicely for my own personal use. just thought i'd share my bookmarklet here.

how

  1. to try it out, create a bookmark (preferably in Chrome) and paste the following into the URL of that new bookmark:

    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 ๐Ÿ’ฒ");
      });

    https://github.com/hchiam/learning-js/blob/main/bookmarklets/blingbling.js

  2. you can now use the following keyboard shortcuts in Chrome to quickly "install" BlingBlingJS on almost any page:

    mac: command + L, then type to search for the bookmark name, then hit enter --> $('...').on now works in the console!

    pc: Ctrl + L, then type to search for the bookmark name, then hit enter --> $('...').on now works in the console!

    Depending on how uniquely you name your bookmark, you can reach it in a few keystrokes. Note that these keyboard shortcuts may not work for you in Firefox. In Firefox, I give short names for the bookmarklets I use often, and place them within easy reach in the bookmark bar (not inside a folder).

    Screen.Recording.2023-07-31.at.9.49.13.PM.mov

Is it a way to replaceChildren within blingblingjs?

Now I'm doing:

  const node = document.createElement('span').innerText = JSON.stringify(variableName, 2, ' ')
  document.getElementById('idname').replaceChildren(node)

But is there a sipmpler way with blingblingjs syntax?

quieter failures

if the selector has no matches, nothing breaks, but the red in the console is annoying

Add $(window).on alias

Currently $(window).on is not setup as an 'addEventListener' alias as per the original bling.js -- would be nice to have this in blingbling too.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.