Skip to content

Instantly share code, notes, and snippets.

@jdillard
Last active July 19, 2018 05:25
Show Gist options
  • Save jdillard/790d5cda88e6add3c53d6ed0304c2797 to your computer and use it in GitHub Desktop.
Save jdillard/790d5cda88e6add3c53d6ed0304c2797 to your computer and use it in GitHub Desktop.
Wiktionary article preview on link hover
<html>
<head>
<script src="https://unpkg.com/tippy.js@2.5.3/dist/tippy.all.min.js"></script>
</head>
<body>
<div id="wiki-template" style="display: none;">
Loading wikipedia summary...
</div>
</body>
</html>
const template = document.querySelector('#wiki-template')
const initialText = template.textContent
const tip = tippy('a[href*="wiktionary.org"]', {
animation: 'shift-toward',
arrow: true,
maxWidth: '300px',
theme: 'light',
html: '#wiki-template',
onShow(instance) {
const wikiPage = instance.reference.href.split("wiktionary.org/wiki")[1].substring(1);
// `this` inside callbacks refers to the popper element
const content = this.querySelector('.tippy-content')
if (tip.loading || content.innerHTML !== initialText) return
tip.loading = true
fetch('https://en.wiktionary.org/w/api.php?action=parse&format=json&origin=*&prop=text|displaytitle&page='+wikiPage).then((resp) => resp.json()).then(data => {
var el = document.createElement( 'html' );
el.innerHTML = Object.values(data.parse.text);
content.innerHTML = "";
content.appendChild(el.getElementsByTagName('ol')[0]);
tip.loading = false
}).catch(e => {
content.innerHTML = 'Loading failed'
tip.loading = false
})
},
onHidden() {
const content = this.querySelector('.tippy-content')
content.innerHTML = initialText
},
// prevent tooltip from displaying over button
popperOptions: {
modifiers: {
preventOverflow: {
enabled: false
},
hide: {
enabled: false
}
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment