Created
February 23, 2018 20:47
-
-
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
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
// 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