Skip to content
forked from gnat/surreal

๐Ÿ—ฟ Mini jQuery alternative. Dependency-free animations. Pairs with htmx. Locality of Behavior. Use one element or arrays transparently. Vanilla querySelector() but better!

License

Notifications You must be signed in to change notification settings

davidwilde/surreal

ย 
ย 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿ—ฟ Surreal - mini jQuery alternative for vanilla JS with inline Locality of Behavior

cover (Art by shahabalizadeh)

Why does this exist?

For devs who love ergonomics! You may appreciate Surreal if:

  • You want to stay as close as possible to Vanilla JS.
  • Hate typing document.querySelector over.. and over..
  • Hate typing addEventListener over.. and over..
  • Really wish document.querySelectorAll had Array functions..
  • Really wish this would work in any inline <script> tag
  • Enjoyed using jQuery selector syntax.
  • Animations, timelines, tweens with no extra libraries.
  • Only 320 lines. No build step. No dependencies.
  • Pairs well with htmx
  • Want fewer layers, less complexity. Are aware of the cargo cult. โœˆ๏ธ

โœจ What will this add to my vanilla javascript?

  • โšก๏ธ Locality of Behavior (LoB) Use me() inside <script>
    • Get an element without creating a unique name: No .class or #id needed!
    • this but better!
    • Want to use it in your CSS <style> tags, too? See our companion script
  • ๐Ÿ”— Call chaining, jQuery style.
  • โ™ป๏ธ Functions work seamlessly on one element or arrays of elements!
    • All functions can use: me(), any(), NodeList, HTMLElement (..or arrays of these!)
    • Get 1 element: me()
    • ..or many elements: any()
    • me() or any() can chain with any Surreal function.
      • me() can be used directly as a single element (like querySelector() or $())
      • any() can use: for / forEach / filter / map (like querySelectorAll() or $())
  • ๐ŸŒ— No forced style: class_add is just an alias of classAdd
    • Use camelCase (Javascript) or snake_case (Python, Rust, PHP, Ruby, SQL, CSS).

๐Ÿค” Why use me() / any() instead of $()

  • ๐Ÿ’ก We solve the classic jQuery code bloat problem: Am I getting 1 element or an array of elements?
    • me() is guaranteed to return 1 element (or first found, or none).
    • any() is guaranteed to return an array (or empty array).
    • No more checks! Write less code! Bonus: Code reads more like self-documenting english.

๐Ÿ‘๏ธ How does it look?

Do surreal things with Locality of Behavior like:

<label for="file-input" >
  <div class="uploader"></div>
  <script>
    me().on("dragover", ev => { halt(ev); me(ev).classAdd('.hover'); console.log("Files in drop zone.") })
    me().on("dragleave", ev => { halt(ev); me(ev).classAdd('.hover'); console.log("Files left drop zone.") })
    me().on("drop", ev => { halt(ev); me(ev).classRemove('.hover').classAdd('.loading'); me('#file-input').attribute('files', ev.dataTransfer.files); me('#form').trigger('change') })
  </script>
</label>

See the Live Example! Then view source.

๐ŸŽ Installation

Surreal is only 320 lines. No build step. No dependencies.

  • Download Surreal and drag surreal.js into a directory of your project.
  • Add <script src="surreal.js"></script> to your <head>.

๐Ÿ“š๏ธ Inspired by

  • jQuery for the chainable syntax we all love.
  • BlingBling.js for modern minimalism.
  • Bliss.js for a focus on single elements and extensibility.
  • Hyperscript for Locality of Behavior and awesome ergonomics.
  • Shout out to Umbrella, Cash, Zepto- Not quite as ergonomic. Requires build step to extend.

โžก๏ธ Usage Overview

๐Ÿ”๏ธ DOM Selection

  • Select one element: me(SELECTOR)
    • SELECTOR can be any of:
      • CSS selector: ".button", "#header", "h1", "body > .block"
      • Variables: body, elt, some_element
      • Events: the event.target will be used.
      • Surreal selectors: me(),any()
      • Adding the , start= parameter provides a starting point to select from, default is document.
        • Example: any('button', start='header').classAdd('red')
    • me() Get current element for Locality of Behavior in <script> without an explicit .class or #id
    • me("body") Gets <body>
    • me(".button") Gets the first <div class="button">...</div>. To get all of them use any()
  • Select one or more elements as an array: any(SELECTOR)
    • Similar to me() but guaranteed to return an array (or empty array).
    • any(".button") Gets all matching elements, example: <div class="button">...</div>
    • Feel free to convert between arrays of elements and single elements: any(me()), me(any(".something"))

โš™๏ธ DOM Functions

  • โ™ป๏ธ All functions work on single elements or arrays of elements.
  • ๐Ÿ”— Start a chain using me() and any()
    • ๐ŸŸข Style A - ๐Ÿ”— Chain style
      • me().classAdd('red') (โญ RECOMMENDED)
        • Alternative, no conveniences: $.me().classAdd('red')
    • ๐ŸŸ  Style B
      • classAdd(me(), 'red')
        • Alternative, no conveniences: $.classAdd($.me(), 'red')
  • ๐ŸŒ Global conveniences help you write less code.
    • globalsAdd() will automatically warn about any clobbering issues. If you prefer no conveniences, just delete globalsAdd()

See: Quick Start and Reference and No Surreal Needed

๐Ÿ”ฅ Quick Start

  • Add a class
    • me().classAdd('red')
    • any("button").classAdd('red')
  • Events
    • me().on("click", ev => me(ev).fade_out() )
    • on(any('button'), 'click', ev => { me(ev).styles('color: red') })
  • Run functions over elements.
    • any('button').run(_ => { alert(_) })
  • Styles / CSS
    • me().styles('color: red')
    • me().styles({ 'color':'red', 'background':'blue' })
  • Attributes
    • me().attribute('active', true)

Timeline animations without any libraries.

<div>I change color every second.
  <script>
    // Locality of Behavior
    me().on("click", async ev => {
      me(ev).styles({ "transition": "background 1s" })
      await sleep(1000)
      me(ev).styles({ "background": "red" })
      await sleep(1000)
      me(ev).styles({ "background": "green" })
      await sleep(1000)
      me(ev).styles({ "background": "blue" })
      await sleep(1000)
      me(ev).styles({ "background": "none" })
      await sleep(1000)
      me(ev).remove()
    })
  </script>
</div>
<div>I fade out and remove myself.
  <script>
    // Keepin it simple! Locality of Behavior.
    me().on("click", ev => { me(ev).fadeOut() })
  </script>
</div>
<div>I change color every second.
<script>
  // Run on load.
  (async (el = me())=>{
    me(el).styles({ "transition": "background 1s" })
    await sleep(1000)
    me(el).styles({ "background": "red" })
    await sleep(1000)
    me(el).styles({ "background": "green" })
    await sleep(1000)
    me(el).styles({ "background": "blue" })
    await sleep(1000)
    me(el).styles({ "background": "none" })
    await sleep(1000)
    me(el).remove()
  })()
</script>
</div>
<script>
  // Keepin it simple! Globally!
  (async ()=>{
    any("button").fadeOut()
  })()
</script>

Array methods

any('button')?.forEach(...)
any('button')?.map(...)

๐Ÿ‘๏ธ Function Reference

Looking for DOM Selectors?

๐Ÿงญ Legend

  • ๐Ÿ”— Chainable off me() and any()
  • ๐ŸŒ Global convenience helper.
  • ๐Ÿ Runnable example.
  • ๐Ÿ”Œ Built-in Plugin

๐Ÿ‘๏ธ At a glance

  • ๐Ÿ”— run
    • It's forEach but less wordy and works on single elements, too!
    • ๐Ÿ me().run(el => { alert(el) })
    • ๐Ÿ any('button').run(el => { alert(el) })
  • ๐Ÿ”— remove
    • ๐Ÿ me().remove()
    • ๐Ÿ any('button').remove()
  • ๐Ÿ”— classAdd or class_add
    • ๐Ÿ me().classAdd('active')
    • Leading . is optional for all class functions, to prevent typical syntax errors with me() and any().
      • me().classAdd('active') and me().classAdd('.active') are equivalent.
  • ๐Ÿ”— classRemove or class_remove
    • ๐Ÿ me().classRemove('active')
  • ๐Ÿ”— classToggle or class_toggle
    • ๐Ÿ me().classToggle('active')
  • ๐Ÿ”— styles
    • ๐Ÿ me().styles('color: red') Add style.
    • ๐Ÿ me().styles({ 'color':'red', 'background':'blue' }) Add multiple styles.
    • ๐Ÿ me().styles({ 'background':null }) Remove style.
  • ๐Ÿ”— attribute or attributes or attr
    • Get: ๐Ÿ me().attribute('data-x')
      • Get is only for single elements. For many, wrap the call in any(...).run(...) or any(...).forEach(...).
    • Set: ๐Ÿme().attribute('data-x', true)
    • Set multiple: ๐Ÿ me().attribute({ 'data-x':'yes', 'data-y':'no' })
    • Remove: ๐Ÿ me().attribute('data-x', null)
    • Remove multiple: ๐Ÿ me().attribute({ 'data-x': null, 'data-y':null })
  • ๐Ÿ”— trigger
    • ๐Ÿ me().trigger('hello')
    • Wraps dispatchEvent
  • ๐Ÿ”— on
    • ๐Ÿ me().on('click', ev => { me(ev).styles('background', 'red') })
    • Wraps addEventListener
  • ๐Ÿ”— off
    • ๐Ÿ me().remove('click')
    • Wraps removeEventListener
  • ๐Ÿ”— offAll
    • ๐Ÿ me().offAll()
  • ๐ŸŒ sleep
    • ๐Ÿ await sleep(1000, ev => { alert(ev) })
    • async version of setTimeout
    • Wonderful for animation timelines.
  • ๐ŸŒ tick
    • ๐Ÿ await tick()
    • await version of rAF / requestAnimationFrame.
    • Animation tick. Waits 1 frame.
    • Great if you need to wait for events to propagate.
  • ๐ŸŒ rAF
    • ๐Ÿ rAF(e => { return e })
    • Animation tick. Fires when 1 frame has passed. Alias of requestAnimationFrame
    • Great if you need to wait for events to propagate.
  • ๐ŸŒ rIC
    • ๐Ÿ rIC(e => { return e })
    • Great time to compute. Fires function when JS is idle. Alias of requestIdleCallback
  • ๐ŸŒ halt
    • ๐Ÿ halt(event)
    • Great to prevent default browser behavior: such as displaying an image vs letting JS handle it.
    • Wrapper for preventDefault
  • ๐ŸŒ createElement or create_element
    • ๐Ÿ el_new = createElement("div"); me().prepend(el_new)
    • Alias of document.createElement
  • ๐ŸŒ onloadAdd or onload_add
    • ๐Ÿ onloadAdd(_ => { alert("loaded!"); })
    • Execute after the DOM is ready. Similar to jquery ready()
    • Queues functions onto window.onload
    • Why? So you don't overwrite window.onload, also predictable sequential loading!

๐Ÿ”Œ Built-in Plugins

Effects

Build your own effects with me().styles({...}) then timelining with CSS transitions using await or callbacks. We ship some common effects:

  • ๐Ÿ”— fadeOut or fade_out

    • Fade out and remove element.
    • Keep element with remove=false.
    • ๐Ÿ me().fadeOut()
    • ๐Ÿ me().fadeOut(ev => { alert("Faded out!") }, 3000) Over 3 seconds then call function.
  • ๐Ÿ”— fadeIn or fade_in

    • Fade in existing element which has opacity: 0
    • ๐Ÿ me().fadeIn()
    • ๐Ÿ me().fadeIn(ev => { alert("Faded in!") }, 3000) Over 3 seconds then call function.

๐Ÿ”ฎ No Surreal Needed

More often than not, Vanilla JS is the easiest way!

Logging

  • ๐ŸŒ console.log() console.warn() console.error()
  • Event logging: ๐Ÿ monitorEvents(me()) See: Chrome Blog

Benchmarking / Time It!

  • ๐Ÿ console.time('name')
  • ๐Ÿ console.timeEnd('name')

Text / HTML Content

  • ๐Ÿ me().textContent = "hello world"
    • XSS Safe! See: MDN
  • ๐Ÿ me().innerHTML = "<p>hello world</p>"
  • ๐Ÿ me().innerText = "hello world"

Children

  • ๐Ÿ me().children
  • ๐Ÿ me().children.hidden = true

Append / Prepend elements.

  • ๐Ÿ me().prepend(el_new)
  • ๐Ÿ me().appendChild(el_new)
  • ๐Ÿ me().insertBefore(el_new, el.firstChild)
  • ๐Ÿ me().insertAdjacentHTML("beforebegin", el_new)

๐Ÿ’Ž Conventions & Tips

  • _ = for temporary or unused variables. Keep it short and sweet!
  • e, el, elt = element
  • e, ev, evt = event
  • f, fn = function
  • Developer ergonomics and simplicity wins.
  • Find the layer where the change needs to touch the least places.
  • Animations are done with me().styles(...) with CSS transitions. Use await sleep(...) for timelining.
  • Dropdowns can be done in pure HTML / CSS.

๐Ÿ”Œ Extending Surreal

Surreal is tiny enough to be modified for a particular use-case; but there is a system if you prefer to effortlessly merge with new versions.

  1. Add your function to Surreal
var $thing = {
  test(e, name) {
    console.log(`Hello ${name} from ${e}`)
    return e
  }
}
$ = {...$, ...$thing}
  1. Is your function chainable? Add it to Surreal sugar()
$.sugars['test'] = (name) => { return $.test($._e, name) }
  1. Your function will automatically will be added globally by globalsAdd() If you do not want this (ex: Naming clash), add it to the restricted list in globalsAdd()

Should your function work with both single elements and arrays of elements? Refer to an existing function to see how to make this work.

Make an issue or pull request if you think people would like to use it! If it's useful enough we may want it in the core!

๐ŸŒ˜ Future

About

๐Ÿ—ฟ Mini jQuery alternative. Dependency-free animations. Pairs with htmx. Locality of Behavior. Use one element or arrays transparently. Vanilla querySelector() but better!

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 78.3%
  • HTML 15.4%
  • CSS 6.3%