javascripthtmltexthighlighttextrange

highlight text on single click (javascript jquery html)


When you double click on a word in all browsers, they automatically highlight the word under the click. But is it possible to find a way to have the exact same thing happen on a single click?

I imagine things involved in this might be: - TextRange stuff; - Reacting to onclick for all paragraphs (or whole body or div), ... but then I have not found anywhere that says how you could tell the browser:

"Hey! Please do that cool thing of highlighting text right under the mouse ... RIGHT NOW ... even though I only single clicked, not double clicked."

Just for clarification: I am not asking to highlight the whole text within a div or paragraph (that would be fairly simple, many explanations are given for that on stackoverflow). Nor am I wanting to do anything like insert a billion spans for each word. I am hoping to find the exact same functionality you get when a double click on text occurs in a browser, but for a single click.

Yes, I plan to do something with the selected text then.


Solution

  • $('#content').click(function() {
        $(this).dblclick();
    });
    

    The browser may restrict this behavior. For instance, if you attempted to .click() a different element by diverting or performed another event. The following answer may also help there:

    Javascript with jQuery: Click and double click on same element, different effect, one disables the other