Jump to content


Multirow selection(getRangeAt) and surroundContents() for text editor

  • Please log in to reply
No replies to this topic

#1 netpumber

  • Members
  • PipPipPip
  • Advanced Member
  • 107 posts

Posted 12 February 2013 - 11:00 AM

Hello out there.

Im trying to create a simple text editor for a web site.
I want to add to him something like the code button in this forum.
So by selecting a specific text, color it's background with gray color.
Here is what i have for now but if i have a multi row text selected(rows created by pressing enter) the function test() doesn't work. It works only if i select a row each time.

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/html"> 

  <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" href="Awesome/css/font-awesome.css">

<body onload="InitEditable()">

  <div style="margin-left:10px;">
      <div class="btn-group">
       <a class="btn" href="#" onclick="fontEdit('bold')"><i class="icon-bold"></i></a>
       <a class="btn" href="#" onclick="fontEdit('italic')"><i class="icon-italic"></i></a>
       <a class="btn" href="#" onclick="fontEdit('underline')"><i class="icon-underline"></i></a>
       <a class="btn" href="#" onclick="test()"><i class="icon-link"></i></a>
        <a class="btn" href="#" onclick="fontEdit('justifyLeft')"><i class="icon-align-left"></i></a>
        <a class="btn" href="#" onclick="fontEdit('justifyCenter')"><i class="icon-align-center"></i></a>
        <a class="btn" href="#" onclick="fontEdit('justifyRight')"><i class="icon-align-right"></i></a>
        <a class="btn" href="#" onclick="fontEdit('justifyFull')"><i class="icon-align-justify"></i></a>

  <div style="margin-left:10px;"><iframe id="textEditor" style="width:500px;height:170px;font-family:arial;font-size:11px;"></iframe></div>

 <script type="text/javascript">

var editorDoc;
var editor;

function InitEditable() 
  editor = document.getElementById("textEditor");
  editorDoc = editor.contentwindow.document;          
  var editorBody = editorDoc.body;

  if ('contentEditable' in editorBody) {
          // allow contentEditable
      editorBody.contentEditable = true;
  }else {  // Firefox earlier than version 3
      if ('designMode' in editorDoc) {
              // turn on designMode
          editorDoc.designMode = "on";                

function fontEdit(x,y)

function test(){

  var range = document.getElementById("textEditor").contentwindow.window.getSelection().getRangeAt(0);

  var newNode = document.createElement('div');
  newNode.style.backgroundColor = "gray";

  return false;  



There must be a problem with surroundContents() and divs but cannot think something to solve it.

Any idea is welcomed!
Thanks in advance.

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users