autocreate.js
Version:
autocreate.js contains a small function that watches for the creation of elements matching a given selector
97 lines (77 loc) • 1.99 kB
HTML
<html>
<head>
<title>autocreate.js</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
</head>
<body>
<p>
<button id="add">Add</button>
<button id="remove">Remove</button>
</p>
<div class="wrapper">
<div class="module">1</div>
<div class="module">2</div>
<div class="module">3</div>
</div>
<script src="https://cdn.jsdelivr.net/u.js/0.34.0/u.min.js"></script>
<script src="autocreate.js"></script>
<script>
/**
* Look for `.module` elements in `.wrapper`.
*/
var module = autocreate({
/**
* Match selector.
*/
selector: '.module',
/**
* Callback which is called with the element matching the selector.
*/
create: (element, context) => {
function update() {
context.value = (Math.random() * 100) | 0;
element.textContent = context.value;
}
context.interval = setInterval(function () {
update();
}, 500);
update();
console.log('create', context);
},
/**
* Callback which is called when the element or one of its parents is removed.
*/
destroy: (element, context) => {
clearInterval(context.interval);
console.log('destroy', context);
},
/**
* If set to true, the element is destroyed immediately. If set to false, the
* element destruction is delayed to detect if the element is moved inside the
* DOM. However, this can cause problems with other plugins. (optional)
*/
destroyDelayed: false,
});
/**
* Add `.module` element to `.wrapper`.
*/
document.querySelector('#add').addEventListener('click', function () {
var element = document.createElement('div');
element.classList.add('module');
element.textContent = 'Init';
document.querySelector('.wrapper').appendChild(element);
});
/**
* Remove single `.module` element from DOM.
*/
document.querySelector('#remove').addEventListener('click', function () {
var element = document.querySelector('.module');
if (element) {
element.parentNode.removeChild(element);
}
});
</script>
</body>
</html>