I have a div which contains a series of span tags, each containing a string of text. I'd like to attach a jQuery click event to all of the spans so that when the text inside any span is clicked, the entire line of text (dom > innerText object) will be auto selected to facilitate the drag/drop or copy/paste of the text string.
For example, my content is...
<div id="mySpans">
<span> This is my text </span>
<span> This is my text </span>
</div>
If the cursor is clicked on any text inside a span, I want to select the text within that span, so that it can be drag/dropped (without the span tags, just the innerText of the span) as a copy.
Does jQuery have an easy means to do this?
EDIT: A more detailed explanation of what I'm trying to accomplish:
Without aid of script, in order to copy a block of text, the user has to manually drag select a selection rectangle across the text block. The text then becomes selected signaling that a click & drag event will pick up all of the selected text. So I'm trying to create script that allows a single click on the text to automatically select the text for the user so they don't have to manually do it themselves.
To check if a span element contains specific text:Use the textContent property on the element to get the text content of the element and its descendants. Use the includes() method to check if the specific text is contained in the span . If it is, the includes() method returns true , otherwise false is returned.
The <span> tag is an inline container used to mark up a part of a text, or a part of a document.
The SpanSelector is a mouse widget that enables selecting a range on an axis. Here, an x-range can be selected on the upper axis; a detailed view of the selected range is then plotted on the lower axis. Note.
use DOM ranges: http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html
var span = ...
var range = document.createRange();
range.setStartBefore(span.firstChild);
range.setEndAfter(span.lastChild);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
Found this core-javascript solution that works well and is hack-free: http://coderzone.org/library/Select-text-in-a-DIV-SPAN-or-table-cell_1047.htm
I took the liberty to change the code a bit so that it accepts the element node as argument instead of an element id.
// Selects text inside an element node.
function selectElementText(el) {
removeTextSelections();
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(el);
range.select();
}
else if (window.getSelection) {
var range = document.createRange();
range.selectNode(el);
window.getSelection().addRange(range);
}
}
// Deselects all text in the page.
function removeTextSelections() {
if (document.selection) document.selection.empty();
else if (window.getSelection) window.getSelection().removeAllRanges();
}
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