Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 12 of 12
  1. #1
    New Coder
    Join Date
    Mar 2009
    Posts
    45
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Text color background

    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

  • #2
    Regular Coder
    Join Date
    Dec 2008
    Location
    Tannhäuser Gate
    Posts
    286
    Thanks
    7
    Thanked 58 Times in 57 Posts
    That should work [tested in FF3 and IE7]:
    Code:
    <!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>

  • #3
    New Coder
    Join Date
    Mar 2009
    Posts
    45
    Thanks
    3
    Thanked 0 Times in 0 Posts
    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

  • #4
    Regular Coder
    Join Date
    Dec 2008
    Location
    Tannhäuser Gate
    Posts
    286
    Thanks
    7
    Thanked 58 Times in 57 Posts
    Have you tried the code I posted? Is this happening only in FF?
    Last edited by freedom_razor; 03-14-2009 at 01:14 PM.

  • #5
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,918
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Quote Originally Posted by freedom_razor View Post
    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

  • #6
    Regular Coder
    Join Date
    Dec 2008
    Location
    Tannhäuser Gate
    Posts
    286
    Thanks
    7
    Thanked 58 Times in 57 Posts
    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:
    Code:
    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.
    Last edited by freedom_razor; 03-14-2009 at 02:11 PM.

  • #7
    New Coder
    Join Date
    Mar 2009
    Posts
    45
    Thanks
    3
    Thanked 0 Times in 0 Posts
    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

  • #8
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,918
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Quote Originally Posted by freedom_razor View Post
    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, 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.

    Code:
    <!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>

    Edit: 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.
    Last edited by Philip M; 03-15-2009 at 10:33 AM.

  • #9
    Regular Coder
    Join Date
    Dec 2008
    Location
    Tannhäuser Gate
    Posts
    286
    Thanks
    7
    Thanked 58 Times in 57 Posts
    I think problems come from browsers trying to produce correct markup. Example
    Code:
    <h2>EXAMPLE TEXT</h2>
    <p>EXAMPLE TEXT</p>
    If you select words in red and use that script, that's the effect in FF:
    Code:
    <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:
    Code:
    <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.
    Last edited by freedom_razor; 03-15-2009 at 10:29 AM.

  • Users who have thanked freedom_razor for this post:

    Philip M (03-15-2009)

  • #10
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,918
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    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>.

  • #11
    New Coder
    Join Date
    Mar 2009
    Posts
    45
    Thanks
    3
    Thanked 0 Times in 0 Posts
    thanks once again.

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

  • #12
    Regular Coder
    Join Date
    Dec 2008
    Location
    Tannhäuser Gate
    Posts
    286
    Thanks
    7
    Thanked 58 Times in 57 Posts
    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.]


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •