Skip to content

Instantly share code, notes, and snippets.

@DC3
Last active March 14, 2019 02:11
Show Gist options
  • Save DC3/cda60df3af17f975a40a to your computer and use it in GitHub Desktop.
Save DC3/cda60df3af17f975a40a to your computer and use it in GitHub Desktop.
do (win = window, doc = window.document, className = 'wrap-placeholder', selector = '[placeholder]') ->
# support placeholder
return if doc.createElement('input').placeholder isnt undefined
modern = doc.addEventListener
setStyles = (node, styles) ->
console.log 'debug', JSON.stringify styles
for name, val of styles
console.log 'debug', [name, val]
node.style[name] = val
return
cssText = 'position:absolute; color:#ACA899; display:inline-block; overflow:hidden;'
hasGetCS = !!win.getComputedStyle
getWrapperStyles = (node) ->
cStyles = if hasGetCS then win.getComputedStyle(node, null) else node.currentStyle
{marginLeft, marginTop, fontSize, fontFamily, paddingLeft} = cStyles
mL = parseInt(marginLeft, 10)
mT = parseInt(marginTop, 10)
isNaN(mL) and mL = 0
(isNaN(mT) or !mT) and mT = 1
marginLeft = "#{mL+3}px"
marginTop = "#{mT}px"
{offsetWidth, offsetHeight} = node
width = "#{offsetWidth - mL}px"
height = "#{offsetHeight}px"
lineHeight = if node.nodeName.toLowerCase() is 'textarea' then '' else height
{cssText, className, fontFamily, fontSize, marginLeft, marginTop, paddingLeft, width, height, lineHeight}
changeHandler = (wrapper, node) ->
wrapper.style.display = if node.value isnt '' then 'none' else 'inline-block'
handle = (node) ->
return unless ((txt = node.getAttribute('placeholder')) or txt.length)
wrapper = doc.createElement('span')
setStyles wrapper, getWrapperStyles(node)
wrapper.appendChild(doc.createTextNode(txt))
wrapper.onclick = -> node.focus()
fnCB = changeHandler.bind(null, wrapper, node)
if typeof node.oninput is 'object'
node.addEventListener 'input', fnCB
else
node.onpropertychange = fnCB
node.parentNode.insertBefore(wrapper, node)
init = ->
#[].slice.call(doc.querySelectorAll(selector)).forEach(handle)
handle(node) for node in doc.querySelectorAll(selector)
return
if doc.readyState is 'complete'
init()
else
if modern
doc.addEventListener 'DOMContentLoaded', init
else
doc.attachEvent 'onreadystatechange', init
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment