Skip to content Skip to sidebar Skip to footer

How To Use The Javascript To Add/remove The Css/colour Style To The Html Page?

I have a simple javascript question in the HTML page. In my case, the user can use the mouse to select some text in the paragrahe, e.g. use the mouse to highlight the 'My name is

Solution 1:

This will do the trick to wrap the selected text with a <span> node. I think you will need to change the getSelection() method in order to make it work in IE, but it works in FF:

function colour(colour) {
  var selection= window.getSelection();
  if (selection.toString()!=="") {
    varrange = selection.getRangeAt(0);
    var span = document.createElement("span");
    span.className = colour;
    span.innerHTML = range.toString();
    range.deleteContents();
    range.insertNode(span);
  }
}

EDIT: The other two functions:

functionclear_colour() {
  var selection=  window.getSelection();
  if (selection.toString()!=="" && 
      selection.anchorNode.parentNode.nodeName==="SPAN") {
    selection.anchorNode.parentNode.className="";
 }
}

functionclear_colour_all() {
  var selection= document.getElementById('content');
  var spans = selection.getElementsByTagName("span");
  for(var i=0;i<spans.length;i++){
  spans[i].className="";
  }
}

It have some weird behavior depending on how you select the text, but now you have something to work with ;)

Solution 2:

You can use the following for selected text coloring (http://jsfiddle.net/7kh8s/):

*This is a very basic one I did, but selected color is working.

<script>functioncolour(colour) {

    getSelectionHTML(colour);

    }

    functiongetSelectionHTML(color)
     {
     if (document.selection && document.selection.createRange) return (document.selection.createRange()).htmlText;
     if (window.getSelection)
     {
     var sel = window.getSelection();
     var html = "";
     for (var i=0;i<sel.rangeCount;i++)
     {
     var d = document.createElement("span");
    d.style.color = color;
     var r = sel.getRangeAt(i);
     var parent_element = r.commonAncestorContainer;
     var prev_html = parent_element.innerHTML;
     r.surroundContents(d);
     html += d.innerHTML;
     parent_element.innerHTML = prev_html;
     }
     return html;
     }
     returnnull;
     }
    </script><p>

        My name is John,
        I live in ABC and I have a car.
        I like to play TV game.

    </p><p><inputtype="button"onclick="colour('red')"value='red'/><inputtype="button"onclick="colour('blue')"value='blue'/></p>

Post a Comment for "How To Use The Javascript To Add/remove The Css/colour Style To The Html Page?"