I Solved It: Text Selected On Mouse Over and Click

Text Selected with Mouseover

It’s essential. Simply, the goal is getting the text in an element selected when doing a mouseover or click event. It sounds quite an easy job. If the HTML element is input tag in a form, here we go with an easiest JavaScript solution:

<input type="text" size="30" onfocus="this.select()" onmouseover="this.select()" value="https://www.princeawful.com/" readonly>

onmouseover="this.select()" attribute will make text selected on mouse over the input element. Similarly, onfocus="this.select()" will do for clicking.

Unfortunately, it DOESN’T WORK on a div element.

Through searching on Google and trying out, I found this thread on stackoverflow, which provides a working solution for selecting text in a div on events.

Well, first we need to define a function in JavaScript:

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);
 }
}

Then it’s time to use jQuery to play. For example, here is my HTML example with an identifier ‘sharecode’:

<div id="sharecode">https://www.princeawful.com</div>

And here is the jQuery codes to locate the div and do the selection on click event:

$(function() {
 $('#sharecode').click(function() {
  SelectText('sharecode');
 });
});

If for mouseover event, use jQuery’s mouseover function:

$(function() {
 $('#sharecode').mouseover(function() {
  SelectText('sharecode');
 });
});

This is it. The workaround is compatible with most modern browsers with JavaScript support. Well done!

Still not believing? Check out my demos below:

Input:

DIV:

https://www.princeawful.com

 

Share Your Opinion