I have a simple non-clickable link within a div that looks like this:
It's meant to be a sharable link that the user can copy paste into other things.
For usability purposes, I want a single left click anywhere within the div to select the entire link:
I don't know much about, javascript/web programming, so I've tried the following:
<div id="share_link" onClick="select_all('share_link')"><%= request.url %></div>
and this javascript
<script type="text/javascript">
function select_all(id) {
document.getElementById(id).focus();
}
</script>
This doesn't work. I'd like to know what's the simplest thing I should do to achieve what I want. I thought about changing the div to a text input or the text within to be a link, but ideally the content within should be read-only, non-editable, and non-clickable
This is achieved completely differently in IE compared to other browsers. The following will work in all major browsers:
<script type="text/javascript">
function select_all(el) {
if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.selection != "undefined" && typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.select();
}
}
</script>
<div onclick="select_all(this)">Link text</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With