Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery: is there a way to highlight the text of a Div when you click on it?

With Jquery is there a way to highlight/select(like if someone were to select it with the mouse) the text inside of a div that i click on? not a textbox, just a normal div.

i'm trying to make a 'short url' box, where when someone clicks on the textarea, it highlights all the text, but it also needs to NOT allow people to change the text in the textbox, but when a textbox is disabled you can't select any text, so i'm trying to do that, i just thought a div would be easiest.

sorry guys i didn't do a great job of explaining what i meant at first, added info above to clarify.

like image 248
android.nick Avatar asked Oct 25 '10 08:10

android.nick


People also ask

How do I highlight a selected DIV?

Click inside the div tag, then select the div tag from the tag selector at the bottom of the Document window.

How do I highlight text in HTML using jQuery?

<mark/> tag is a html 5 element used to highlight the text. Thats it. Hope this small code snippet will help you for achieving highlighting text using jQuery.


1 Answers

Right, this isn't about background colours, it's about selecting the text.

First set an input to readonly, stopping people changing the value:

<input type="text" readonly="readonly" value="ABC" />

Then using jQuery (or similar) to select the text once it's been clicked:

$('input').click(function() {
    $(this).select(); 
});

You should style this input as you see fit, perhaps to make it look like a normal bit of text, take a look at this jsFiddle for a further demonstration.

like image 60
Ben Everard Avatar answered Nov 14 '22 22:11

Ben Everard