...

View Full Version : Text color background



csam0003
03-12-2009, 10:13 AM
Hi,
I have the following code which when the user clicks a button, the text background color should change to red, however nothing is happening!

var sel = content.document.getSelection();
var range = sel.getRangeAt(0);
var newNode = document.createElement("span");
newNode.setAttribute('style', 'background: red');
range.surroundContents(newNode);

Any ideas? Is the sel.getRangeAt(0) correct?

Thank you as always

Regards

freedom_razor
03-12-2009, 12:48 PM
That should work [tested in FF3 and IE7]:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<script type="text/javascript">
//- <![CDATA[
function changeBG(){
var sel = window.getSelection ? window.getSelection() : document.selection.createRange(); // FF : IE
if(sel.getRangeAt){ // thats for FF
var range = sel.getRangeAt(0);
var newNode = document.createElement("span");
newNode.setAttribute('style', 'background: red');
range.surroundContents(newNode);
} else { //and thats for IE7
sel.pasteHTML('<span style="background:red">'+sel.htmlText+'</span>');
}
}
//- ]]>
</script>
<p>EXAMPLE TEXT</p>
<p>EXAMPLE TEXT</p>
<a href="#" onclick="changeBG(); return false;">clickme</a>
</body>
</html>

csam0003
03-14-2009, 12:45 PM
Thanks alot for your promt reply.
I found the issue! I had to use content.window.getSelection rather than window.getSelection.

Although the text color background is working, when I do change the text color background, the text highlighted changes position (i.e. sometimes the text goes on a new line).

var sel = content.window.getSelection();
var range = sel.getRangeAt(0);
var newNode = document.createElement("span");
newNode.setAttribute('style','background: pink');
range.surroundContents(newNode);

Can someone please help?!I've been on this for 2 days.

Thank you for your time

freedom_razor
03-14-2009, 01:04 PM
Have you tried the code I posted? Is this happening only in FF?

Philip M
03-14-2009, 01:24 PM
Have you tried the code I posted? Is this happening only in FF?

It works fine if "EXAMPLE TEXT" is selected but not if just "TEXT" is selected.

the text highlighted changes position (i.e. sometimes the text goes on a new line).

My attempts to fix it have not been successful :(

freedom_razor
03-14-2009, 01:59 PM
Mhm, it does seem to be buggy. Somehow for example whole links get selected and moved into <p>, or </p> tag gets removed.
With following markup seems to work well in both IE7 and FF3:

EXAMPLE TEXT<br />
EXAMPLE TEXT<br />
------------<br />

<p><a href="#" onclick="changeBG(); return false;">clickme</a><p>


Seems to be choking on any selection that includes closed HTML tags in it.

csam0003
03-15-2009, 12:35 AM
Thanks alot guys for your input. I am trying in Firefox as I wish to highlight the text in Firefox.
I noticed that the issue is that a new line is being created everytime the text is highlighted. a friend of mine mentioned something about the innerhtml??!?!

Thanks once again

Philip M
03-15-2009, 09:28 AM
Seems to be choking on any selection that includes closed HTML tags in it.

In fact the problem seems to be the lack of an opening tag.

This appears to work in IE and FF (no change to the script):-
BUT NOTE what is probably a kludge, :eek: namely two </p> tags separated by a space at the end of each paragraph. This is required to stop the unwanted deletion of the line feed/carriage return if the last word of the text is selected.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<script type="text/javascript">
//- <![CDATA[
function changeBG(){
var sel = window.getSelection ? window.getSelection() : document.selection.createRange(); // FF : IE
if(sel.getRangeAt){ // thats for FF
var range = sel.getRangeAt(0);
var newNode = document.createElement("span");
newNode.setAttribute('style', 'background: red');
range.surroundContents(newNode);
} else { //and thats for IE7
sel.pasteHTML('<span style="background:red">'+sel.htmlText+'</span>');
}
}
//- ]]
</script>


<p>EXAMPLE TEXT Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque condimentum volutpat odio. Vivamus faucibus diam et neque. Aliquam erat volutpat. In hac habitasse platea dictumst. Suspendisse at sem vel ante dignissim venenatis. Maecenas vestibulum, leo quis porttitor volutpat, nunc libero molestie sem, nec sodales neque sem ac eros. Donec et felis. Fusce nec felis. </p> </p></br>

<p> EXAMPLE TEXT Pellentesque in diam. Nulla sed dolor quis enim vestibulum hendrerit. Donec est magna, egestas laoreet, aliquam eget, convallis nec, metus. Donec adipiscing pharetra risus. Curabitur eleifend, libero eget sollicitudin malesuada, elit lectus pretium est, at blandit odio est eget risus. Aliquam augue neque, feugiat vel, accumsan ac, blandit eget, erat. </p> </p></br>


<a href="#" onclick="changeBG(); return false;">Click me to change the background color</a>
</body>
</html>


Still not perfect - screws up and inserts LF/CRs if user selects beyond the end of the para. i.e. drags mouse down into blank area below text.

freedom_razor
03-15-2009, 10:20 AM
I think problems come from browsers trying to produce correct markup. Example

<h2>EXAMPLE TEXT</h2>
<p>EXAMPLE TEXT</p>

If you select words in red and use that script, that's the effect in FF:

<h2>EXAMPLE </h2><span style="background: red none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;"><h2>TEXT</h2>
<p>EXAMPLE</p></span><p> TEXT</p>

Instead of wrapping 2 SPAN tags around the text in different paragraphs, it is trying to separate words outside of selection and wrap them in H2 or P tags, and then wrap the selection in SPAN adding also correct markup for whatever tags the selection was wrapped in [so, adding another H2 for the first word, as it was originally in H2, and adding P for the bottom word.

IE is trying to do the same, just in a bit different way:

<H2>EXAMPLE <SPAN style="BACKGROUND: red"><H2>TEXT</H2><P>EXAMPLE</P></SPAN> TEXT</H2>
Does more damage to markup that FF here, wrapping extra H2 around both paragraphs, selected or not.

Anyway, I have not found any solution to this, apart from using different markup, as I mentioned before [BR for new line works ok it seems].
I also thought about retrieving selected text and formatting it with regexp and then pasting back, but seeing as both browsers are internally adding extra tags, I'm not sure it would work at all. Seems like a bug in both IE and FF.

Philip M
03-15-2009, 10:53 AM
It seems to work OK provided the opening tag <p>or <h4> is on a separate line from the actual text:-


<h4>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque condimentum volutpat odio. Vivamus faucibus diam et neque. Aliquam erat volutpat. In hac habitasse platea dictumst. Suspendisse at sem vel ante dignissim venenatis. Maecenas vestibulum, leo quis porttitor volutpat, nunc libero molestie sem, nec sodales neque sem ac eros. Donec et felis. Fusce nec felis. <br />
<br />
Pellentesque in diam. Nulla sed dolor quis enim vestibulum hendrerit. Donec est magna, egestas laoreet, aliquam eget, convallis nec, metus. Donec adipiscing pharetra risus. Curabitur eleifend, libero eget sollicitudin malesuada, elit lectus pretium est, at blandit odio est eget risus. Aliquam augue neque, feugiat vel, accumsan ac, blandit eget, erat. <br />
</h4>
<br><br>
<a href="#" onclick="changeBG(); return false;">Click me to change background color of selected text</a>

BUT all the text from which the selection can be made must be in the same size - it appears that para 1 cannot be <h4> and the second para <h5>.

csam0003
03-15-2009, 12:35 PM
thanks once again.

Is there another way round this?maybe a better approach?

freedom_razor
03-15-2009, 01:01 PM
I've found some articles about that problem. The mess browsers make with adding extra tags is actually a mechanism to prevent producing invalid markup. So, not a bug but a feature.
I've tried stripping/formatting the selection with regexp, didn't work, because browsers add their tags to selection anyway [IE even adds some stupid commas out of nowhere].

At this stage I'm out of ideas, sorry. You can always make sure that your markup allows for highlighting, as I mentioned before. As long as there are no closed tags in the text for selecting, it is working fine [so, use BR instead of P etc.]. Obviously, that leaves you with little options for formatting...
You could probably think about innerHTML and going this way, but that depends on what you are trying to achieve. If the text for selecting is included in some set element of the page, you could retrieve whole content of that element, format the selected part [assuming it would be possible to pinpoint the selection in the content], and replace the content with formatted one [SPAN added etc.]



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum