Skip to content

Instantly share code, notes, and snippets.

@vordan
Created February 23, 2018 20:47
Show Gist options
  • Save vordan/c3e3f3a9aade0eb12070c394247a101d to your computer and use it in GitHub Desktop.
Save vordan/c3e3f3a9aade0eb12070c394247a101d to your computer and use it in GitHub Desktop.
[DIV Text Selected On Mouse Over and Click] Working solution for selecting text in a div on events #JavaScript
// https://www.princeawful.com/807/solved-text-selected-mouse-and-click
function SelectText(element) {
 var doc = document
  , text = doc.getElementById(element)
  , range, selection
 ;
 if (doc.body.createTextRange) {
  range = document.body.createTextRange();
  range.moveToElementText(text);
  range.select();
 } else if (window.getSelection) {
  selection = window.getSelection();
  range = document.createRange();
  range.selectNodeContents(text);
  selection.removeAllRanges();
  selection.addRange(range);
 }
}
<div id="sharecode">https://www.princeawful.com</div>
$(function() {
 $('#sharecode').click(function() {
  SelectText('sharecode');
 });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment