digabi/koe-ohje

Copy math img to clipboard

Closed this issue · 1 comments

Implementation example:

In Markup:

<button class="copy" data-latex="x+\\frac{1}{x}">Copy</button>

In JS-code:

$('.copy').on('mousedown', e => {
    const latex = $(e.target).data('latex')
    console.log(latex)
    const el = createMathImg(latex)
    selectElementContents(el)
    e.preventDefault()
    document.execCommand('copy')
    document.body.removeChild(el)
})

function createMathImg(latex) {
    console.log('createEq')
    const img = document.createElement('img')
    img.setAttribute('alt', latex)
    img.setAttribute('src', '/math.svg?latex='+ encodeURIComponent(latex))
    document.body.appendChild(img)
    return img
}

function selectElementContents(el) {
    const range = document.createRange()
    range.selectNode(el)
    const sel = window.getSelection()
    sel.removeAllRanges()
    sel.addRange(range)
}

done