Skip to content Skip to sidebar Skip to footer

How To Make Selected Text Bold/italic/underlined In Javascript?

I'm trying to work on a webpage that allows users to write their own notes for a school project, and my idea was to let them bold/italicize/underline their text using buttons. As o

Solution 1:

You can use execCommand(). This API was meant for developing text editors. The 3 buttons utilize the very versatile execCommand() and the writing element is a plain div enabled with the attribute contenteditable.

SNIPPET

<!DOCTYPE html><html><head><metacharset='utf-8'><style>body {
      font: 40016px/1.4'serif';
      }
    #editor1 {
      border: 3px inset grey;
      height: 100px;
      width: 381px;
      margin: 10px auto 0;
     }
    fieldset {
      margin: 2px auto 15px;
      width: 358px;
    }
    button {
      width: 5ex;
      text-align: center;
      padding: 1px3px;
    }
  </style></head><body><divid="editor1"contenteditable="true">
     The quick brown fox jumped over the lazy dog.
  </div><fieldset><buttonclass="fontStyle"onclick="document.execCommand('italic',false,null);"title="Italicize Highlighted Text"><i>I</i></button><buttonclass="fontStyle"onclick="document.execCommand( 'bold',false,null);"title="Bold Highlighted Text"><b>B</b></button><buttonclass="fontStyle"onclick="document.execCommand( 'underline',false,null);"><u>U</u></button></fieldset>

Solution 2:

Textarea does not allow such things. I would suggest you to use something like ckeditor. It will do the job for you neatly. But if you still want to do it yourself, you need to use a div with contenteditable tag.

Good Luck !

Solution 3:

With textarea you cannot achieve that, use divs instead, so you can do something like this:

$(document).ready(function(){
$('.boldText').click(function(){
   $('.container').toggleClass("bold");
});
$('.italicText').click(function(){
  $('.container').toggleClass("italic");
});
$('.underlineText').click(function(){
  $('.container').toggleClass("underline");
});



});
div.container {
    width: 300px;
    height: 100px;
    border: 1px solid #ccc;
    padding: 5px;
}
.bold{
  font-weight:bold;
}
.italic{
  font-style :italic;
}
.underline{
 text-decoration: underline;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script><divclass="container"contentEditable></div><br/><inputtype="button"class="boldText"value="Bold"><inputtype="button"class="italicText"value="Italic"><inputtype="button"class="underlineText"value="Underline">

Post a Comment for "How To Make Selected Text Bold/italic/underlined In Javascript?"