Reputation: 2657
I'm trying to make it so that a div can only be highlighted one word at a time.
So for example, from the above sentence, I could highlight/select only be highlighted
but not only be highli
. If I put my mouse at the position of the highli
, it would either not have selected highlighted
yet, or it would have selected the entire highlighted
already.
To clarify, by highlight/select I mean what happens when you click on a word, hold your mouse button down, and drag to another point in the text.
I haven't been able to find any examples of this, but I also feel like I've seen something similar before. Is there a simple way to do this, for example some CSS rule? Or is the only way to roll out some custom javascript handling document selects?
Upvotes: 2
Views: 63
Reputation: 976
Word selection can be enforced by wrapping each word into a span element and using user-select:all to force element wide selection for instance
<style>
.word {
user-select: all;
}
</style>
<span class="word">this</span>
<span class="word">test</span>
<span class="word">is</span>
<span class="word">a</span>
Now this can be annoying to do by hand so javascript can come to the rescue for instance this:
<style>
.word {
-moz-user-select: all;
-webkit-user-select: all;
-ms-user-select: all;
user-select: all;
}
</style>
<p class="selected-by-word">Hello this is a text where selection should be word-wide.</p>
<p class="selected-by-word">Another text with word-wide selection.</p>
<script>
let textToSplit = document.getElementsByClassName('selected-by-word')
Array.prototype.forEach.call(textToSplit, function (anElement) {
anElement.innerHTML = anElement.innerHTML.replace(/\w+/g, "<span class='word'>$&</span>")
})
</script>
All element having the class selected-by-word will be set for word-wide selection.
Upvotes: 2