download/copy fidddle

download or copy text

by borsna

HTML

<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/citation.js"></script>
<div>
  <pre id="content">
@misc{ Nobody06,
       author = "Nobody Jr",
       title = "My Article",
       year = "2006" 
}
  </pre>
</div>
<select id="citationFormat" onchange="changeCitationFormat(this)">
  <option value="bibtex" data-mimetype="application/x-bibtex" data-file-extension="bibtex">BibTeX</option>
  <option value="bibtext" data-mimetype="application/x-bibtex" data-file-extension="bib">Bib.TXT</option>
  <option value="ris" data-mimetype="application/x-bibtex" data-file-extension="ris">RIS</option>
</select>

<button onclick="downloadCitation()">download</button>
<button onclick="copyCitation()">copy</button>

JavaScript

const Cite = require('citation-js')
let cite = new Cite('10.5878/mw0p-6812')

let output = cite.format('bibtex', {
  format: 'text',
  template: 'apa',
  lang: 'en-US'
});
document.getElementById("content").innerHTML = output


function changeCitationFormat(){
  var e = document.getElementById("citationFormat");
  var formatOption = e.options[e.selectedIndex];
}

function downloadCitation() {
  var e = document.getElementById("citationFormat");
  var formatOption = e.options[e.selectedIndex];
  console.log(formatOption.dataset.fileExtension);

  var filename = "citation."+formatOption.dataset.fileExtension;
  var content  = document.getElementById("content").innerHTML;
  
  var element = document.createElement('a');
  element.setAttribute('href', 
  										 'data:'+formatOption.dataset.mimetype+';'+
                       'charset=utf-8,' + encodeURIComponent(content));
  
  element.setAttribute('download', filename);
  element.style.display = 'none';
  document.body.appendChild(element);
  element.click();
  document.body.removeChild(element);

}

function copyCitation() {
  var content = document.getElementById("content");
	copyTextToClipboard(content.innerHTML)
}

function fallbackCopyTextToClipboard(text) {
  var textArea = document.createElement("textarea");
  textArea.value = text;
  
  // Avoid scrolling to bottom
  textArea.style.top = "0";
  textArea.style.left = "0";
  textArea.style.position = "fixed";

  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Fallback: Copying text command was ' + msg);
  } catch (err) {
    console.error('Fallback: Oops, unable to copy', err);
  }

  document.body.removeChild(textArea);
}

function copyTextToClipboard(text) {
  if (!navigator.clipboard) {
    fallbackCopyTextToClipboard(text);
    return;
  }
 ...