visu wrote:
Hi this is a question asked in this group two years back..
No answer for this question till date.
now i am in the same situation of the questioner.. to find a solution
for this problem.
Can any one help me in this regard.?
The question is:
----------------------------------------------------------------------------------------------------
Wondering if anyone can tell me if it's possible to have Javascript
select the contents of a div tag with a unique id by clicking
somewhere in the contents of that div tag?
I want to make it as easy as possible for users to copy the contents
of the div tag for pasting in another page. So, instead of having them
use the mouse to drag the selection, which can sometimes be annoying,
I'd like to have them click anywhere within the div tag and have the
text automatically selected, and then they can simply right click and
select 'Copy'.
If this is possible, can anyone give me some advice on how to achieve
it?
As an alternative, if a div tag won't respond to an onClick event
itself, would it be possible to select the contents of that div tag
(assume, for eg, that it has the unique id of "Copy1") by clicking on
a button?
Any help with this would be much appreciated!
Much warmth,
Murray
----------------------------------------------------------------------------------------------------
thanx for both questioner and the person who is going to reveal a
solution for this.
This sounds like an incredibly ambitious project and it would help you
to first gain some experience with JavaScript/HTML on some more trivial
projects before tackling this. Once you do, you'll have some insight
into some of the questions that come up.
So, all div tags will respond no problem to an onclick event (always
call it onclick, never onClick - javascript is case-sensitive and so
is XHTML, so it's best to just adopt this convention). However, the
question is - *what* do you want copied. Do you want the entire
contents of a div tag? If so, then a recursive function is the way to
get the text of an element:
function getText(node) {
var txt = '';
if (node.nodeType == 3) // i.e. it's a text node
txt += node.nodeValue;
for (var i=0; i < node.childNodes.length; i++)
txt += getText(node.childNodes[i]);
return txt;
};
Or do you want the div tag itself? Then you can just clone the node:
var newNode = node.cloneNode(true); // optional argument is true if
you want to clone children as well
Or do you want only a portion of the contents of the div tag? How are
you going to have the user specify which portion is to be selected if
they just click once and aren't dragging?
Also, I would discourage you from trying to mess with the right-click
button. Browsers have control over the right-click context menu and
there is little you can do to turn that off reliably in all browsers.
Give them a "paste" button instead.
Alternativley, you might want to just give users a textarea they can
dump text into.
-David