onmount
Run something when a DOM element appears and when it exits.
No dependencies. Legacy IE compatible. 1kb .min.gz.
Overview
Detecting elements
Run something to initialize an element on its first appearance.
onmount =
Polling for changes
Call $.onmount()
everytime your code changes.
→
$ //=> 'working...'
jQuery integration
jQuery is optional; use it to poll on popular events. →
Cleanups
Supply a 2nd function to onmount() to execute something when the node is first detached. →
$ documentbodyinnerHTML = '' $ //=> 'button was removed'
What for?
Onmount is a safe, reliable, idempotent, and testable way to attach JavaScript behaviors to DOM nodes. It's great for common websites that are not Single-Page Apps. Read more on its premise and motivation.
rsjs (Reasonable System for JavaScript Structure) is a great standard that onmount fits perfectly into.
Usage
Onmount is available via npm and Bower.
npm install onmount
bower install onmount
It can be used as a CommonJS module or on its own. It doesn't require jQuery, but if jQuery is found, it'll attach itself to it as $.onmount
.
onmount = // With CommonJS (ie, Browserify)windowonmount // with no module loaders:$onmount // with jQuery
API
See: API
Browser compatibility
All modern browsers and IE8+. For legacy IE, use it with jQuery 1.x.
Examples
Examples are available in the source repo. See examples →
Thanks
onmount © 2015+, Rico Sta. Cruz. Released under the MIT License.
Authored and maintained by Rico Sta. Cruz with help from contributors (list).
ricostacruz.com · GitHub @rstacruz · Twitter @rstacruz