Jump to content


Grabbing Selected/Highlighted Text in JS


4 replies to this topic

#1 Demonslay

    P2L Jedi

  • Members
  • PipPipPip
  • 970 posts
  • Gender:Male
  • Location:A strange world where water falls out of the sky... for no reason.
  • Interests:Graphic Design, Coding, Splinter Cell, Cats

Posted 13 November 2006 - 11:01 PM

Arg!
I've been for hours, trying to figure out how to grab selected text and display it with an alert box (my debugging method).
I've studied many, many scripts, including that of IPB, which is perhaps a million leagues above my head.
I've gone with the basics, but Firefox only gives me an empty string. If I try to output any of the other options, and just tossing aside the if statements, it gives undefined...
<script type="text/javascript">
function selected(){
	var myTextRange = document.getElementById('test').getSelection();
	alert(myTextRange); // Doesn't work
	
	var txt = '';
	var foundIn = '';
	if (window.getSelection)
	{
		txt = window.getSelection().getRangeAt(0);
		foundIn = 'window.getSelection()';
	}
	else if (document.getSelection)
	{
		txt = document.getSelection();
		foundIn = 'document.getSelection()';
	}
	else if (document.selection)
	{
		txt = document.selection.createRange().text;
		foundIn = 'document.selection.createRange()';
	}
	else return;
	
	alert(foundIn); // For me gives 'window.getSelection()'
	alert(txt); // Gives nothing
}
</script>

<textarea id="test">Text</textarea><br />
<input type="button" id="button" onclick="selected()" value="Test" />

I'm trying to implement this for an sort of mini WYSIWYG editor for my shoutbox, using the common feature you see on IPB that allows you to encase highlighted text with tags.
I've also studied the source of three different WYSIWYG editors, but to no help. All give the same basis code, which for some reason works when I use them, yet I put it into my own code and get nothing.
I read blogs/comments and even example code from sites like Dynamic Drive, and same thing... works online for their sites, but not for my site or localhost. -_-

#2 rc69

    PHP Master PD

  • P2L Staff
  • PipPipPipPip
  • 3,827 posts
  • Gender:Male
  • Location:Here
  • Interests:Web Development

Posted 14 November 2006 - 01:09 AM

Well, i've never tried my hand at getting selected text through JS (or any other means), but i have looked at it a bit here and there out of curiosity. In my studies, i can remember one thing. Firefox doesn't support selected text. I don't know why... That's just what i remember (and as i just tested it out on my forums, i'd believe it).
But i do have good news... For some reason, it supports selected text within textareas. So, i'll give you the JS that phpBB uses, and maybe you can work something similar out...
The function to pay attention to is mozWrap(), the rest is just for show.
// From http://www.massless.org/mozedit/
function mozWrap(txtarea, open, close)
{
	var selLength = txtarea.textLength;
	var selStart = txtarea.selectionStart;
	var selEnd = txtarea.selectionEnd;
	if (selEnd == 1 || selEnd == 2) 
		selEnd = selLength;

	var s1 = (txtarea.value).substring(0,selStart);
	var s2 = (txtarea.value).substring(selStart, selEnd)
	var s3 = (txtarea.value).substring(selEnd, selLength);
	txtarea.value = s1 + open + s2 + close + s3;
	return;
}

function bbstyle(bbnumber) {
	var txtarea = form.MessagePost;
	txtarea.focus();
	donotinsert = false;
	theSelection = false;
	bblast = 0;
	if (bbnumber == -1) { // Close all open tags & default button names
		while (bbcode[0]) {
			butnumber = arraypop(bbcode) - 1;
			txtarea.value += bbtags[butnumber + 1];
			buttext = eval('form.addbbcode' + butnumber + '.value');
			eval('form.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
		}
		imageTag = false; // All tags are closed including image tags :D
		txtarea.focus();
		return;
	}

	if ((clientVer >= 4) && is_ie && is_win)
	{
		theSelection = document.selection.createRange().text; // Get text selection
		if (theSelection) {
			// Add tags around selection
			document.selection.createRange().text = bbtags[bbnumber] + theSelection + bbtags[bbnumber+1];
			txtarea.focus();
			theSelection = '';
			return;
		}
	}
	else if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0))
	{
		mozWrap(txtarea, bbtags[bbnumber], bbtags[bbnumber+1]);
		return;
	}

	// Find last occurance of an open tag the same as the one just clicked
	for (i = 0; i < bbcode.length; i++) {
		if (bbcode[i] == bbnumber+1) {
			bblast = i;
			donotinsert = true;
		}
	}

	if (donotinsert) {		// Close all open tags up to the one just clicked & default button names
		while (bbcode[bblast]) {
				butnumber = arraypop(bbcode) - 1;
				txtarea.value += bbtags[butnumber + 1];
				buttext = eval('form.addbbcode' + butnumber + '.value');
				eval('form.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
				imageTag = false;
			}
			txtarea.focus();
			return;
	} else { // Open tags
		if (imageTag && (bbnumber != 14)) {		// Close image tag before adding another
			txtarea.value += bbtags[15];
			lastValue = arraypop(bbcode) - 1;	// Remove the close image tag from the list
			form.addbbcode14.value = "Img";	// Return button back to normal state
			imageTag = false;
		}

		// Open tag
		txtarea.value += bbtags[bbnumber];
		if ((bbnumber == 14) && (imageTag == false)) imageTag = 1; // Check to stop additional tags after an unclosed image tag
		arraypush(bbcode,bbnumber+1);
		eval('form.addbbcode'+bbnumber+'.value += "*"');
		txtarea.focus();
		return;
	}
	storeCaret(txtarea);
}

function quoteSelection(){
	theSelection = false;
	theSelection = document.selection.createRange().text; // Get text selection
	if (theSelection) {
		// Add tags around selection
		emoticon('[quote]\n' + theSelection + '\n[/quote]\n');
		form.MessagePost.focus();
		theSelection = '';
		return;
	}else{
		alert('{L_NO_TEXT_SELECTED}');
	}
}

function storeCaret(textEl) {
	if (textEl.createTextRange) textEl.caretPos = document.selection.createRange().duplicate();
}
And the textarea that it is used on:
<textarea name="post" rows="10" cols="80" wrap="virtual" tabindex="3" class="post" onSelect="storeCaret(this);" onClick="storeCaret(this);" onKeyUp="storeCaret(this);"></textarea>

p.s. If you've actually managed to find a site that obtains the selected text on a page in FireFox and displays it/uses it some how, please, send me a PM. I would love to see how they did it -_-

Edited by rc69, 14 November 2006 - 01:11 AM.


#3 Demonslay

    P2L Jedi

  • Members
  • PipPipPip
  • 970 posts
  • Gender:Male
  • Location:A strange world where water falls out of the sky... for no reason.
  • Interests:Graphic Design, Coding, Splinter Cell, Cats

Posted 15 November 2006 - 03:00 PM

Ok, thanks. I'll try it out a little later when I can. ^_^

I actually found quite a few that worked in Firefox, for outside of textareas, which was the most common I found. But I couldn't get them to work on my page for some reason.
An example: http://www.quirksmod...s/selected.html

#4 rc69

    PHP Master PD

  • P2L Staff
  • PipPipPipPip
  • 3,827 posts
  • Gender:Male
  • Location:Here
  • Interests:Web Development

Posted 16 November 2006 - 02:51 AM

Well, don't i feel like an idiot for posting all of that code...

Anywho, i think the problem is that you copied the code wrong.
function selected(){
	var txt = '';
	var foundIn = '';
	if (window.getSelection){
		txt = window.getSelection(); // No .getRangeAt(0) at quirksmode, it also happens to be in the right block for FF.
		foundIn = 'window.getSelection()';
	}else if (document.getSelection){
		txt = document.getSelection();
		foundIn = 'document.getSelection()';
	}else if (document.selection){
		txt = document.selection.createRange().text;
		foundIn = 'document.selection.createRange()';
	}else{
		return;
	}
	
	alert('Found:\n'+txt+'\nIn:\n'+foundIn);
}


#5 Demonslay

    P2L Jedi

  • Members
  • PipPipPip
  • 970 posts
  • Gender:Male
  • Location:A strange world where water falls out of the sky... for no reason.
  • Interests:Graphic Design, Coding, Splinter Cell, Cats

Posted 16 November 2006 - 09:23 PM

Opps, lol, I forgot to take that out before posting that. I was just testing that out.


Yay! The code you gave me works! (The mozWrap one) ;)

Thanks! :mellow:

Edited by Demonslay, 16 November 2006 - 09:23 PM.






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users