\n\n\n\n### Multiple File Uploads\n\n``` python\nfrom fasthtml.common import *\nfrom pathlib import Path\n\napp, rt = fast_app()\n\nupload_dir = Path(\"filez\")\nupload_dir.mkdir(exist_ok=True)\n\n@rt('/')\ndef get():\n return Titled(\"Multiple File Upload Demo\",\n Article(\n Form(hx_post=upload_many, hx_target=\"#result-many\")(\n Input(type=\"file\", name=\"files\", multiple=True),\n Button(\"Upload\", type=\"submit\", cls='secondary'),\n ),\n Div(id=\"result-many\")\n )\n )\n\ndef FileMetaDataCard(file):\n return Article(\n Header(H3(file.filename)),\n Ul(\n Li('Size: ', file.size), \n Li('Content Type: ', file.content_type),\n Li('Headers: ', file.headers),\n )\n ) \n\n@rt\nasync def upload_many(files: list[UploadFile]):\n cards = []\n for file in files:\n cards.append(FileMetaDataCard(file))\n filebuffer = await file.read()\n (upload_dir / file.filename).write_bytes(filebuffer)\n return cards\n\nserve()\n```\n\nLine 13 \nEvery form rendered with the\n[`Form`](https://AnswerDotAI.github.io/fasthtml/api/xtend.html#form) FT\ncomponent defaults to `enctype=\"multipart/form-data\"`\n\nLine 14 \nDon’t forget to set the `Input` FT Component’s type to `file` and assign\nthe multiple attribute to `True`\n\nLine 32 \nThe upload view should receive a `list` containing the [Starlette\nUploadFile](https://www.starlette.io/requests/#request-files) type. You\ncan add other form variables\n\nLine 34 \nIterate through the files\n\nLine 35 \nWe can access the metadata of the card (filename, size, content_type,\nheaders), a quick and safe process. We add that to the cards variable\n\nLine 36 \nIn order to access the contents contained within a file we use the\n`await` method to read() it. As files may be quite large or contain bad\ndata, this is a seperate step from accessing metadata\n\nLine 37 \nThis step shows how to use Python’s built-in `pathlib.Path` library to\nwrite the file to disk.\n\n\n\n\n\n+++\ntitle = \"Reference\"\n+++\n\n## Contents\n\n* [htmx Core Attributes](#attributes)\n* [htmx Additional Attributes](#attributes-additional)\n* [htmx CSS Classes](#classes)\n* [htmx Request Headers](#request_headers)\n* [htmx Response Headers](#response_headers)\n* [htmx Events](#events)\n* [htmx Extensions](/extensions)\n* [JavaScript API](#api)\n* [Configuration Options](#config)\n\n## Core Attribute Reference {#attributes}\n\nThe most common attributes when using htmx.\n\n
\n\n| Attribute | Description |\n|--------------------------------------------------|--------------------------------------------------------------------------------------------------------------------|\n| [`hx-get`](@/attributes/hx-get.md) | issues a `GET` to the specified URL |\n| [`hx-post`](@/attributes/hx-post.md) | issues a `POST` to the specified URL |\n| [`hx-on*`](@/attributes/hx-on.md) | handle events with inline scripts on elements |\n| [`hx-push-url`](@/attributes/hx-push-url.md) | push a URL into the browser location bar to create history |\n| [`hx-select`](@/attributes/hx-select.md) | select content to swap in from a response |\n| [`hx-select-oob`](@/attributes/hx-select-oob.md) | select content to swap in from a response, somewhere other than the target (out of band) |\n| [`hx-swap`](@/attributes/hx-swap.md) | controls how content will swap in (`outerHTML`, `beforeend`, `afterend`, ...) |\n| [`hx-swap-oob`](@/attributes/hx-swap-oob.md) | mark element to swap in from a response (out of band) |\n| [`hx-target`](@/attributes/hx-target.md) | specifies the target element to be swapped |\n| [`hx-trigger`](@/attributes/hx-trigger.md) | specifies the event that triggers the request |\n| [`hx-vals`](@/attributes/hx-vals.md) | add values to submit with the request (JSON format) |\n\n
\n\n## Additional Attribute Reference {#attributes-additional}\n\nAll other attributes available in htmx.\n\n
\n\n| Attribute | Description |\n|------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------|\n| [`hx-boost`](@/attributes/hx-boost.md) | add [progressive enhancement](https://en.wikipedia.org/wiki/Progressive_enhancement) for links and forms |\n| [`hx-confirm`](@/attributes/hx-confirm.md) | shows a `confirm()` dialog before issuing a request |\n| [`hx-delete`](@/attributes/hx-delete.md) | issues a `DELETE` to the specified URL |\n| [`hx-disable`](@/attributes/hx-disable.md) | disables htmx processing for the given node and any children nodes |\n| [`hx-disabled-elt`](@/attributes/hx-disabled-elt.md) | adds the `disabled` attribute to the specified elements while a request is in flight |\n| [`hx-disinherit`](@/attributes/hx-disinherit.md) | control and disable automatic attribute inheritance for child nodes |\n| [`hx-encoding`](@/attributes/hx-encoding.md) | changes the request encoding type |\n| [`hx-ext`](@/attributes/hx-ext.md) | extensions to use for this element |\n| [`hx-headers`](@/attributes/hx-headers.md) | adds to the headers that will be submitted with the request |\n| [`hx-history`](@/attributes/hx-history.md) | prevent sensitive data being saved to the history cache |\n| [`hx-history-elt`](@/attributes/hx-history-elt.md) | the element to snapshot and restore during history navigation |\n| [`hx-include`](@/attributes/hx-include.md) | include additional data in requests |\n| [`hx-indicator`](@/attributes/hx-indicator.md) | the element to put the `htmx-request` class on during the request |\n| [`hx-inherit`](@/attributes/hx-inherit.md) | control and enable automatic attribute inheritance for child nodes if it has been disabled by default |\n| [`hx-params`](@/attributes/hx-params.md) | filters the parameters that will be submitted with a request |\n| [`hx-patch`](@/attributes/hx-patch.md) | issues a `PATCH` to the specified URL |\n| [`hx-preserve`](@/attributes/hx-preserve.md) | specifies elements to keep unchanged between requests |\n| [`hx-prompt`](@/attributes/hx-prompt.md) | shows a `prompt()` before submitting a request |\n| [`hx-put`](@/attributes/hx-put.md) | issues a `PUT` to the specified URL |\n| [`hx-replace-url`](@/attributes/hx-replace-url.md) | replace the URL in the browser location bar |\n| [`hx-request`](@/attributes/hx-request.md) | configures various aspects of the request |\n| [`hx-sync`](@/attributes/hx-sync.md) | control how requests made by different elements are synchronized |\n| [`hx-validate`](@/attributes/hx-validate.md) | force elements to validate themselves before a request |\n| [`hx-vars`](@/attributes/hx-vars.md) | adds values dynamically to the parameters to submit with the request (deprecated, please use [`hx-vals`](@/attributes/hx-vals.md)) |\n\n
\n\n## CSS Class Reference {#classes}\n\n
\n\n| Class | Description |\n|-----------|-------------|\n| `htmx-added` | Applied to a new piece of content before it is swapped, removed after it is settled.\n| `htmx-indicator` | A dynamically generated class that will toggle visible (opacity:1) when a `htmx-request` class is present\n| `htmx-request` | Applied to either the element or the element specified with [`hx-indicator`](@/attributes/hx-indicator.md) while a request is ongoing\n| `htmx-settling` | Applied to a target after content is swapped, removed after it is settled. The duration can be modified via [`hx-swap`](@/attributes/hx-swap.md).\n| `htmx-swapping` | Applied to a target before any content is swapped, removed after it is swapped. The duration can be modified via [`hx-swap`](@/attributes/hx-swap.md).\n\n
\n\n## HTTP Header Reference {#headers}\n\n### Request Headers Reference {#request_headers}\n\n
\n\n| Header | Description |\n|--------|-------------|\n| `HX-Boosted` | indicates that the request is via an element using [hx-boost](@/attributes/hx-boost.md)\n| `HX-Current-URL` | the current URL of the browser\n| `HX-History-Restore-Request` | \"true\" if the request is for history restoration after a miss in the local history cache\n| `HX-Prompt` | the user response to an [hx-prompt](@/attributes/hx-prompt.md)\n| `HX-Request` | always \"true\"\n| `HX-Target` | the `id` of the target element if it exists\n| `HX-Trigger-Name` | the `name` of the triggered element if it exists\n| `HX-Trigger` | the `id` of the triggered element if it exists\n\n
\n\n### Response Headers Reference {#response_headers}\n\n
\n\n| Header | Description |\n|------------------------------------------------------|-------------|\n| [`HX-Location`](@/headers/hx-location.md) | allows you to do a client-side redirect that does not do a full page reload\n| [`HX-Push-Url`](@/headers/hx-push-url.md) | pushes a new url into the history stack\n| [`HX-Redirect`](@/headers/hx-redirect.md) | can be used to do a client-side redirect to a new location\n| `HX-Refresh` | if set to \"true\" the client-side will do a full refresh of the page\n| [`HX-Replace-Url`](@/headers/hx-replace-url.md) | replaces the current URL in the location bar\n| `HX-Reswap` | allows you to specify how the response will be swapped. See [hx-swap](@/attributes/hx-swap.md) for possible values\n| `HX-Retarget` | a CSS selector that updates the target of the content update to a different element on the page\n| `HX-Reselect` | a CSS selector that allows you to choose which part of the response is used to be swapped in. Overrides an existing [`hx-select`](@/attributes/hx-select.md) on the triggering element\n| [`HX-Trigger`](@/headers/hx-trigger.md) | allows you to trigger client-side events\n| [`HX-Trigger-After-Settle`](@/headers/hx-trigger.md) | allows you to trigger client-side events after the settle step\n| [`HX-Trigger-After-Swap`](@/headers/hx-trigger.md) | allows you to trigger client-side events after the swap step\n\n
\n\n## Event Reference {#events}\n\n
\n\n| Event | Description |\n|-------|-------------|\n| [`htmx:abort`](@/events.md#htmx:abort) | send this event to an element to abort a request\n| [`htmx:afterOnLoad`](@/events.md#htmx:afterOnLoad) | triggered after an AJAX request has completed processing a successful response\n| [`htmx:afterProcessNode`](@/events.md#htmx:afterProcessNode) | triggered after htmx has initialized a node\n| [`htmx:afterRequest`](@/events.md#htmx:afterRequest) | triggered after an AJAX request has completed\n| [`htmx:afterSettle`](@/events.md#htmx:afterSettle) | triggered after the DOM has settled\n| [`htmx:afterSwap`](@/events.md#htmx:afterSwap) | triggered after new content has been swapped in\n| [`htmx:beforeCleanupElement`](@/events.md#htmx:beforeCleanupElement) | triggered before htmx [disables](@/attributes/hx-disable.md) an element or removes it from the DOM\n| [`htmx:beforeOnLoad`](@/events.md#htmx:beforeOnLoad) | triggered before any response processing occurs\n| [`htmx:beforeProcessNode`](@/events.md#htmx:beforeProcessNode) | triggered before htmx initializes a node\n| [`htmx:beforeRequest`](@/events.md#htmx:beforeRequest) | triggered before an AJAX request is made\n| [`htmx:beforeSwap`](@/events.md#htmx:beforeSwap) | triggered before a swap is done, allows you to configure the swap\n| [`htmx:beforeSend`](@/events.md#htmx:beforeSend) | triggered just before an ajax request is sent\n| [`htmx:beforeTransition`](@/events.md#htmx:beforeTransition) | triggered before the [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API) wrapped swap occurs\n| [`htmx:configRequest`](@/events.md#htmx:configRequest) | triggered before the request, allows you to customize parameters, headers\n| [`htmx:confirm`](@/events.md#htmx:confirm) | triggered after a trigger occurs on an element, allows you to cancel (or delay) issuing the AJAX request\n| [`htmx:historyCacheError`](@/events.md#htmx:historyCacheError) | triggered on an error during cache writing\n| [`htmx:historyCacheMiss`](@/events.md#htmx:historyCacheMiss) | triggered on a cache miss in the history subsystem\n| [`htmx:historyCacheMissError`](@/events.md#htmx:historyCacheMissError) | triggered on a unsuccessful remote retrieval\n| [`htmx:historyCacheMissLoad`](@/events.md#htmx:historyCacheMissLoad) | triggered on a successful remote retrieval\n| [`htmx:historyRestore`](@/events.md#htmx:historyRestore) | triggered when htmx handles a history restoration action\n| [`htmx:beforeHistorySave`](@/events.md#htmx:beforeHistorySave) | triggered before content is saved to the history cache\n| [`htmx:load`](@/events.md#htmx:load) | triggered when new content is added to the DOM\n| [`htmx:noSSESourceError`](@/events.md#htmx:noSSESourceError) | triggered when an element refers to a SSE event in its trigger, but no parent SSE source has been defined\n| [`htmx:onLoadError`](@/events.md#htmx:onLoadError) | triggered when an exception occurs during the onLoad handling in htmx\n| [`htmx:oobAfterSwap`](@/events.md#htmx:oobAfterSwap) | triggered after an out of band element as been swapped in\n| [`htmx:oobBeforeSwap`](@/events.md#htmx:oobBeforeSwap) | triggered before an out of band element swap is done, allows you to configure the swap\n| [`htmx:oobErrorNoTarget`](@/events.md#htmx:oobErrorNoTarget) | triggered when an out of band element does not have a matching ID in the current DOM\n| [`htmx:prompt`](@/events.md#htmx:prompt) | triggered after a prompt is shown\n| [`htmx:pushedIntoHistory`](@/events.md#htmx:pushedIntoHistory) | triggered after an url is pushed into history\n| [`htmx:responseError`](@/events.md#htmx:responseError) | triggered when an HTTP response error (non-`200` or `300` response code) occurs\n| [`htmx:sendError`](@/events.md#htmx:sendError) | triggered when a network error prevents an HTTP request from happening\n| [`htmx:sseError`](@/events.md#htmx:sseError) | triggered when an error occurs with a SSE source\n| [`htmx:sseOpen`](/events#htmx:sseOpen) | triggered when a SSE source is opened\n| [`htmx:swapError`](@/events.md#htmx:swapError) | triggered when an error occurs during the swap phase\n| [`htmx:targetError`](@/events.md#htmx:targetError) | triggered when an invalid target is specified\n| [`htmx:timeout`](@/events.md#htmx:timeout) | triggered when a request timeout occurs\n| [`htmx:validation:validate`](@/events.md#htmx:validation:validate) | triggered before an element is validated\n| [`htmx:validation:failed`](@/events.md#htmx:validation:failed) | triggered when an element fails validation\n| [`htmx:validation:halted`](@/events.md#htmx:validation:halted) | triggered when a request is halted due to validation errors\n| [`htmx:xhr:abort`](@/events.md#htmx:xhr:abort) | triggered when an ajax request aborts\n| [`htmx:xhr:loadend`](@/events.md#htmx:xhr:loadend) | triggered when an ajax request ends\n| [`htmx:xhr:loadstart`](@/events.md#htmx:xhr:loadstart) | triggered when an ajax request starts\n| [`htmx:xhr:progress`](@/events.md#htmx:xhr:progress) | triggered periodically during an ajax request that supports progress events\n\n
\n\n## JavaScript API Reference {#api}\n\n
\n\n| Method | Description |\n|-------|-------------|\n| [`htmx.addClass()`](@/api.md#addClass) | Adds a class to the given element\n| [`htmx.ajax()`](@/api.md#ajax) | Issues an htmx-style ajax request\n| [`htmx.closest()`](@/api.md#closest) | Finds the closest parent to the given element matching the selector\n| [`htmx.config`](@/api.md#config) | A property that holds the current htmx config object\n| [`htmx.createEventSource`](@/api.md#createEventSource) | A property holding the function to create SSE EventSource objects for htmx\n| [`htmx.createWebSocket`](@/api.md#createWebSocket) | A property holding the function to create WebSocket objects for htmx\n| [`htmx.defineExtension()`](@/api.md#defineExtension) | Defines an htmx [extension](https://htmx.org/extensions)\n| [`htmx.find()`](@/api.md#find) | Finds a single element matching the selector\n| [`htmx.findAll()` `htmx.findAll(elt, selector)`](@/api.md#find) | Finds all elements matching a given selector\n| [`htmx.logAll()`](@/api.md#logAll) | Installs a logger that will log all htmx events\n| [`htmx.logger`](@/api.md#logger) | A property set to the current logger (default is `null`)\n| [`htmx.off()`](@/api.md#off) | Removes an event listener from the given element\n| [`htmx.on()`](@/api.md#on) | Creates an event listener on the given element, returning it\n| [`htmx.onLoad()`](@/api.md#onLoad) | Adds a callback handler for the `htmx:load` event\n| [`htmx.parseInterval()`](@/api.md#parseInterval) | Parses an interval declaration into a millisecond value\n| [`htmx.process()`](@/api.md#process) | Processes the given element and its children, hooking up any htmx behavior\n| [`htmx.remove()`](@/api.md#remove) | Removes the given element\n| [`htmx.removeClass()`](@/api.md#removeClass) | Removes a class from the given element\n| [`htmx.removeExtension()`](@/api.md#removeExtension) | Removes an htmx [extension](https://htmx.org/extensions)\n| [`htmx.swap()`](@/api.md#swap) | Performs swapping (and settling) of HTML content\n| [`htmx.takeClass()`](@/api.md#takeClass) | Takes a class from other elements for the given element\n| [`htmx.toggleClass()`](@/api.md#toggleClass) | Toggles a class from the given element\n| [`htmx.trigger()`](@/api.md#trigger) | Triggers an event on an element\n| [`htmx.values()`](@/api.md#values) | Returns the input values associated with the given element\n\n
\n\n\n## Configuration Reference {#config}\n\nHtmx has some configuration options that can be accessed either programmatically or declaratively. They are\nlisted below:\n\n
\n\n| Config Variable | Info |\n|---------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| `htmx.config.historyEnabled` | defaults to `true`, really only useful for testing |\n| `htmx.config.historyCacheSize` | defaults to 10 |\n| `htmx.config.refreshOnHistoryMiss` | defaults to `false`, if set to `true` htmx will issue a full page refresh on history misses rather than use an AJAX request |\n| `htmx.config.defaultSwapStyle` | defaults to `innerHTML` |\n| `htmx.config.defaultSwapDelay` | defaults to 0 |\n| `htmx.config.defaultSettleDelay` | defaults to 20 |\n| `htmx.config.includeIndicatorStyles` | defaults to `true` (determines if the indicator styles are loaded) |\n| `htmx.config.indicatorClass` | defaults to `htmx-indicator` |\n| `htmx.config.requestClass` | defaults to `htmx-request` |\n| `htmx.config.addedClass` | defaults to `htmx-added` |\n| `htmx.config.settlingClass` | defaults to `htmx-settling` |\n| `htmx.config.swappingClass` | defaults to `htmx-swapping` |\n| `htmx.config.allowEval` | defaults to `true`, can be used to disable htmx's use of eval for certain features (e.g. trigger filters) |\n| `htmx.config.allowScriptTags` | defaults to `true`, determines if htmx will process script tags found in new content |\n| `htmx.config.inlineScriptNonce` | defaults to `''`, meaning that no nonce will be added to inline scripts |\n| `htmx.config.inlineStyleNonce` | defaults to `''`, meaning that no nonce will be added to inline styles |\n| `htmx.config.attributesToSettle` | defaults to `[\"class\", \"style\", \"width\", \"height\"]`, the attributes to settle during the settling phase |\n| `htmx.config.wsReconnectDelay` | defaults to `full-jitter` |\n| `htmx.config.wsBinaryType` | defaults to `blob`, the [the type of binary data](https://developer.mozilla.org/docs/Web/API/WebSocket/binaryType) being received over the WebSocket connection |\n| `htmx.config.disableSelector` | defaults to `[hx-disable], [data-hx-disable]`, htmx will not process elements with this attribute on it or a parent |\n| `htmx.config.withCredentials` | defaults to `false`, allow cross-site Access-Control requests using credentials such as cookies, authorization headers or TLS client certificates |\n| `htmx.config.timeout` | defaults to 0, the number of milliseconds a request can take before automatically being terminated |\n| `htmx.config.scrollBehavior` | defaults to 'instant', the scroll behavior when using the [show](@/attributes/hx-swap.md#scrolling-scroll-show) modifier with `hx-swap`. The allowed values are `instant` (scrolling should happen instantly in a single jump), `smooth` (scrolling should animate smoothly) and `auto` (scroll behavior is determined by the computed value of [scroll-behavior](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior)). |\n| `htmx.config.defaultFocusScroll` | if the focused element should be scrolled into view, defaults to false and can be overridden using the [focus-scroll](@/attributes/hx-swap.md#focus-scroll) swap modifier. |\n| `htmx.config.getCacheBusterParam` | defaults to false, if set to true htmx will append the target element to the `GET` request in the format `org.htmx.cache-buster=targetElementId` |\n| `htmx.config.globalViewTransitions` | if set to `true`, htmx will use the [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API) API when swapping in new content. |\n| `htmx.config.methodsThatUseUrlParams` | defaults to `[\"get\", \"delete\"]`, htmx will format requests with these methods by encoding their parameters in the URL, not the request body |\n| `htmx.config.selfRequestsOnly` | defaults to `true`, whether to only allow AJAX requests to the same domain as the current document |\n| `htmx.config.ignoreTitle` | defaults to `false`, if set to `true` htmx will not update the title of the document when a `title` tag is found in new content |\n| `htmx.config.scrollIntoViewOnBoost` | defaults to `true`, whether or not the target of a boosted element is scrolled into the viewport. If `hx-target` is omitted on a boosted element, the target defaults to `body`, causing the page to scroll to the top. |\n| `htmx.config.triggerSpecsCache` | defaults to `null`, the cache to store evaluated trigger specifications into, improving parsing performance at the cost of more memory usage. You may define a simple object to use a never-clearing cache, or implement your own system using a [proxy object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy) |\n| `htmx.config.responseHandling` | the default [Response Handling](@/docs.md#response-handling) behavior for response status codes can be configured here to either swap or error |\n| `htmx.config.allowNestedOobSwaps` | defaults to `true`, whether to process OOB swaps on elements that are nested within the main response element. See [Nested OOB Swaps](@/attributes/hx-swap-oob.md#nested-oob-swaps). |\n\n
\n\nYou can set them directly in javascript, or you can use a `meta` tag:\n\n```html\n\n```
# 🗿 Surreal\n### Tiny jQuery alternative for plain Javascript with inline [Locality of Behavior](https://htmx.org/essays/locality-of-behaviour/)!\n\n![cover](https://user-images.githubusercontent.com/24665/171092805-b41286b2-be4a-4aab-9ee6-d604699cc507.png)\n(Art by [shahabalizadeh](https://www.deviantart.com/shahabalizadeh))\n\n\n## Why does this exist?\n\nFor devs who love ergonomics! You may appreciate Surreal if:\n\n* You want to stay as close as possible to Vanilla JS.\n* Hate typing `document.querySelector` over.. and over..\n* Hate typing `addEventListener` over.. and over..\n* Really wish `document.querySelectorAll` had Array functions..\n* Really wish `this` would work in any inline `\n\n```\n\nSee the [Live Example](https://gnat.github.io/surreal/example.html)! Then [view source](https://github.com/gnat/surreal/blob/main/example.html).\n\n## 🎁 Install\n\nSurreal is only 320 lines. No build step. No dependencies.\n\n[📥 Download](https://raw.githubusercontent.com/gnat/surreal/main/surreal.js) into your project, and add `` in your ``\n\nOr, 🌐 via CDN: ``\n\n## ⚡ Usage\n\n### 🔍️ DOM Selection\n\n* Select **one** element: `me(...)`\n * Can be any of:\n * CSS selector: `\".button\"`, `\"#header\"`, `\"h1\"`, `\"body > .block\"`\n * Variables: `body`, `e`, `some_element`\n * Events: `event.currentTarget` will be used.\n * Surreal selectors: `me()`,`any()`\n * Choose the start location in the DOM with the 2nd arg. (Default: `document`)\n * 🔥 `any('button', me('#header')).classAdd('red')`\n * Add `.red` to any `
\n```\n```html\n
I fade out and remove myself.\n \n
\n```\n```html\n
Change color every second.\n \n
\n```\n```html\n\n```\n#### Array methods\n```js\nany('button')?.forEach(...)\nany('button')?.map(...)\n```\n\n## 👁️ Functions\nLooking for [DOM Selectors](#selectors)?\nLooking for stuff [we recommend doing in vanilla JS](#no-surreal)?\n### 🧭 Legend\n* 🔗 Chainable off `me()` and `any()`\n* 🌐 Global shortcut.\n* 🔥 Runnable example.\n* 🔌 Built-in Plugin\n### 👁️ At a glance\n\n* 🔗 `run`\n * It's `forEach` but less wordy and works on single elements, too!\n * 🔥 `me().run(e => { alert(e) })`\n * 🔥 `any('button').run(e => { alert(e) })`\n* 🔗 `remove`\n * 🔥 `me().remove()`\n * 🔥 `any('button').remove()`\n* 🔗 `classAdd` 🌗 `class_add` 🌗 `addClass` 🌗 `add_class`\n * 🔥 `me().classAdd('active')`\n * Leading `.` is **optional**\n * Same thing: `me().classAdd('active')` 🌗 `me().classAdd('.active')`\n* 🔗 `classRemove` 🌗 `class_remove` 🌗 `removeClass` 🌗 `remove_class`\n * 🔥 `me().classRemove('active')`\n* 🔗 `classToggle` 🌗 `class_toggle` 🌗 `toggleClass` 🌗 `toggle_class`\n * 🔥 `me().classToggle('active')`\n* 🔗 `styles`\n * 🔥 `me().styles('color: red')` Add style.\n * 🔥 `me().styles({ 'color':'red', 'background':'blue' })` Add multiple styles.\n * 🔥 `me().styles({ 'background':null })` Remove style.\n* 🔗 `attribute` 🌗 `attributes` 🌗 `attr`\n * Get: 🔥 `me().attribute('data-x')`\n * For single elements.\n * For many elements, wrap it in: `any(...).run(...)` or `any(...).forEach(...)`\n * Set: 🔥`me().attribute('data-x', true)`\n * Set multiple: 🔥 `me().attribute({ 'data-x':'yes', 'data-y':'no' })`\n * Remove: 🔥 `me().attribute('data-x', null)`\n * Remove multiple: 🔥 `me().attribute({ 'data-x': null, 'data-y':null })`\n* 🔗 `send` 🌗 `trigger`\n * 🔥 `me().send('change')`\n * 🔥 `me().send('change', {'data':'thing'})`\n * Wraps `dispatchEvent`\n* 🔗 `on`\n * 🔥 `me().on('click', ev => { me(ev).styles('background', 'red') })`\n * Wraps `addEventListener`\n* 🔗 `off`\n * 🔥 `me().off('click', fn)`\n * Wraps `removeEventListener`\n* 🔗 `offAll`\n * 🔥 `me().offAll()`\n* 🔗 `disable`\n * 🔥 `me().disable()`\n * Easy alternative to `off()`. Disables click, key, submit events.\n* 🔗 `enable`\n * 🔥 `me().enable()`\n * Opposite of `disable()`\n* 🌐 `createElement` 🌗 `create_element`\n * 🔥 `e_new = createElement(\"div\"); me().prepend(e_new)`\n * Alias of [document.createElement](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement)\n* 🌐 `sleep`\n * 🔥 `await sleep(1000, ev => { alert(ev) })`\n * `async` version of `setTimeout`\n * Wonderful for animation timelines.\n* 🌐 `halt`\n * 🔥 `halt(event)`\n * When recieving an event, stop propagation, and prevent default actions (such as form submit).\n * Wrapper for [stopPropagation](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation) and [preventDefault](https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n* 🌐 `tick`\n * 🔥 `await tick()`\n * `await` version of `rAF` / `requestAnimationFrame`.\n * Waits for 1 frame (browser paint).\n * Useful to guarantee CSS properties are applied, and events have propagated.\n* 🌐 `rAF`\n * 🔥 `rAF(e => { return e })`\n * Calls after 1 frame (browser paint). Alias of [requestAnimationFrame](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)\n * Useful to guarantee CSS properties are applied, and events have propagated.\n* 🌐 `rIC`\n * 🔥 `rIC(e => { return e })`\n * Calls when Javascript is idle. Alias of [requestIdleCallback](https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback)\n* 🌐 `onloadAdd` 🌗 `onload_add` 🌗 `addOnload` 🌗 `add_onload`\n * 🔥 `onloadAdd(_ => { alert(\"loaded!\"); })`\n * 🔥 ``\n * Execute after the DOM is ready. Similar to jquery `ready()`\n * Add to `window.onload` while preventing overwrites of `window.onload` and predictable loading!\n * Alternatives:\n * Skip missing elements using `?.` example: `me(\"video\")?.requestFullscreen()`\n * Place ``\n * Inspired by the CSS \"next sibling\" combinator `+` but in reverse `-`\n* Or, use a relative start.\n * 🔥 `
`\n\n#### Ignore call chain when element is missing.\n* 🔥 `me(\"#i_dont_exist\")?.classAdd('active')`\n* No warnings: 🔥 `me(\"#i_dont_exist\", document, false)?.classAdd('active')`\n\n## 🔌 Your own plugin\n\nFeel free to edit Surreal directly- but if you prefer, you can use plugins to effortlessly merge with new versions.\n\n```javascript\nfunction pluginHello(e) {\n function hello(e, name=\"World\") {\n console.log(`Hello ${name} from ${e}`)\n return e // Make chainable.\n }\n // Add sugar\n e.hello = (name) => { return hello(e, name) }\n}\n\nsurreal.plugins.push(pluginHello)\n```\n\nNow use your function like: `me().hello(\"Internet\")`\n\n* See the included `pluginEffects` for a more comprehensive example.\n* Your functions are added globally by `globalsAdd()` If you do not want this, add it to the `restricted` list.\n* Refer to an existing function to see how to make yours work with 1 or many elements.\n\nMake an [issue](https://github.com/gnat/surreal/issues) or [pull request](https://github.com/gnat/surreal/pulls) if you think people would like to use it! If it's useful enough we'll want it in core.\n\n### ⭐ Awesome Surreal examples, plugins, and resources: [awesome-surreal](https://github.com/gnat/awesome-surreal) !\n\n## 📚️ Inspired by\n\n* [jQuery](https://jquery.com/) for the chainable syntax we all love.\n* [BlingBling.js](https://github.com/argyleink/blingblingjs) for modern minimalism.\n* [Bliss.js](https://blissfuljs.com/) for a focus on single elements and extensibility.\n* [Hyperscript](https://hyperscript.org) for Locality of Behavior and awesome ergonomics.\n* Shout out to [Umbrella](https://umbrellajs.com/), [Cash](https://github.com/fabiospampinato/cash), [Zepto](https://zeptojs.com/)- Not quite as ergonomic. Requires build step to extend.\n\n## 🌘 Future\n* Always more `example.html` goodies!\n* Automated browser testing perhaps with:\n * [Fava](https://github.com/fabiospampinato/fava). See: https://github.com/avajs/ava/issues/24#issuecomment-885949036\n * [Ava](https://github.com/avajs/ava/blob/main/docs/recipes/browser-testing.md)\n * [jsdom](https://github.com/jsdom/jsdom)\n * [jsdom notes](https://github.com/jsdom/jsdom#executing-scripts)# 🌘 CSS Scope Inline\n\n![cover](https://github.com/gnat/css-scope-inline/assets/24665/c4935c1b-34e3-4220-9d42-11f064999a57)\n(Art by [shahabalizadeh](https://www.artstation.com/artwork/zDgdd))\n\n## Why does this exist?\n\n* You want an easy inline vanilla CSS experience without Tailwind CSS.\n* Hate creating unique class names over.. and over.. to use once.\n* You want to co-locate your styles for ⚡️ [Locality of Behavior (LoB)](https://htmx.org/essays/locality-of-behaviour/)\n* You wish `this` would work in `\n \n
\n```\nSee the [Live Example](https://gnat.github.io/css-scope-inline/example.html)! Then [view source](https://github.com/gnat/css-scope-inline/blob/main/example.html).\n\n## 🌘 How does it work?\n\nThis uses `MutationObserver` to monitor the DOM, and the moment a `\n red\n
green
\n
green
\n
green
\n
yellow
\n
blue
\n
green
\n
green
\n\n\n
\n red\n
green
\n
green
\n
green
\n
yellow
\n
blue
\n
green
\n
green
\n
\n```\n\n### CSS variables and child elements\nAt first glance, **Tailwind Example 2** looks very promising! Exciting ...but:\n* 🔴 **Every child style requires an explicit selector.**\n * Tailwinds' shorthand advantages sadly disappear.\n * Any more child styles added in Tailwind will become longer than vanilla CSS.\n * This limited example is the best case scenario for Tailwind.\n* 🔴 Not visible on github: **no highlighting for properties and units** begins to be painful.\n```html\n\n\n \n \n \n \n \n \n \n
\n \n
Home
\n
Team
\n
Profile
\n
Settings
\n
Log Out
\n
\n\n \n
\n
Home
\n
Team
\n
Profile
\n
Settings
\n
Log Out
\n
\n\n \n
\n
Home
\n
Team
\n
Profile
\n
Settings
\n
Log Out
\n
\n \n\n```\n## 🔎 Technical FAQ\n* Why do you use `querySelectorAll()` and not just process the `MutationObserver` results directly?\n * This was indeed the original design; it will work well up until you begin recieving subtrees (ex: DOM swaps with [htmx](https://htmx.org), ajax, jquery, etc.) which requires walking all subtree elements to ensure we do not miss a `