Skip to content

Instantly share code, notes, and snippets.

@thure
Last active August 29, 2015 14:00
Show Gist options
  • Save thure/841b8f961cba27a0293f to your computer and use it in GitHub Desktop.
Save thure/841b8f961cba27a0293f to your computer and use it in GitHub Desktop.
DOM element maker, which returns a pointer to the element and a promise that is resolved on insertion. Requires the additional styles to work.
define(['q', 'underscore'], function(q, _){
return function(opts){
var opts = opts || {}
, parent = opts.parent || document.body
, innerHtml = opts.html || ''
, tagName = opts.tagName || 'div'
, className = opts.className ? opts.className + ' trackInsertion' : 'trackInsertion'
, data = opts.data || {}
, attrs = opts.attrs || {}
, d = q.defer()
, win8 = opts.win8 || false;
var el = document.createElement(tagName)
, listener = function(e){
if(e.animationName === 'nodeInserted'){
if(e.target === el){
// resolve when the original element's insertion is triggered
d.resolve(el);
el.classList.remove('trackInsertion');
}else{
// notify of any tracked children's insertion events as well
d.notify(e);
}
}
};
el.addEventListener('animationstart', listener, opts.capture);
el.addEventListener('webkitAnimationStart', listener, opts.capture);
_.each(attrs, function(val, att){
el.setAttribute(att, val);
});
_.each(data, function(val, att){
el.setAttribute('data-' + att, val);
});
el.className = className;
el.innerHTML = !win8 ? innerHtml : window.toStaticHTML(innerHtml);
parent.appendChild(el);
return {
el: el,
promise: d.promise
}
};
});
@keyframes nodeInserted {
from {
opacity: 0.99;
}
to {
opacity: 1;
}
}
@-webkit-keyframes nodeInserted {
from { clip: rect(1px, auto, auto, auto); }
to { clip: rect(0px, auto, auto, auto); }
}
.trackInsertion {
-webkit-animation-duration: 0.1s;
-webkit-animation-name: nodeInserted;
animation-duration: 0.1s;
animation-name: nodeInserted;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment