Last active
November 28, 2018 08:26
-
-
Save fhdalikhan/68c001a4f7c9d22fc3bdd6e23781dd8f to your computer and use it in GitHub Desktop.
On mouse down, tooltip and copy selection text example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var tooltip, // global variables oh my! Refactor when deploying! | |
hidetooltiptimer | |
function createtooltip(){ // call this function ONCE at the end of page to create tool tip object | |
tooltip = document.createElement('div') | |
tooltip.style.cssText = | |
'position:absolute; background:black; color:white; padding:4px;z-index:10000;' | |
+ 'border-radius:2px; font-size:12px;box-shadow:3px 3px 3px rgba(0,0,0,.4);' | |
+ 'opacity:0;transition:opacity 0.3s' | |
tooltip.innerHTML = 'Copied!' | |
document.body.appendChild(tooltip) | |
} | |
function showtooltip(e){ | |
var evt = e || event | |
clearTimeout(hidetooltiptimer) | |
tooltip.style.left = evt.pageX - 10 + 'px' | |
tooltip.style.top = evt.pageY + 15 + 'px' | |
tooltip.style.opacity = 1 | |
hidetooltiptimer = setTimeout(function(){ | |
tooltip.style.opacity = 0 | |
}, 500) | |
} | |
function getSelectionText(){ | |
var selectedText = "" | |
if (window.getSelection){ // all modern browsers and IE9+ | |
selectedText = window.getSelection().toString() | |
} | |
return selectedText | |
} | |
function copySelectionText(){ | |
var copysuccess // var to check whether execCommand successfully executed | |
try{ | |
copysuccess = document.execCommand("copy") // run command to copy selected text to clipboard | |
} catch(e){ | |
copysuccess = false | |
} | |
return copysuccess | |
} | |
createtooltip(); // create tooltip by calling it ONCE per page. See "Note" below | |
$('.toSelect').on('mouseup', function(event) { | |
var selected = getSelectionText() // call getSelectionText() to see what was selected | |
if (selected.length > 0){ // if selected text length is greater than 0 | |
var copysuccess = copySelectionText() // copy user selected text to clipboard | |
showtooltip(event) | |
} | |
}); | |
// html example | |
<ul> | |
<li class="tooltipContainer"> | |
<span class="toSelect" id="26238"> | |
<a href="#">First Page SubTitle</a> | |
</span> | |
</li> | |
<li class="tooltipContainer"> | |
<span class="toSelect" id="14303"> | |
<a href="#">Second Page Subtitle</a> | |
</span> | |
</li> | |
</ul> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment