Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check, the selected text is bold or not (contenteditable)

I'm implementing a custom text editor using html inbuilt contenteditable feature. I need to know when user selected a text on the text editor whether it's bold or not.

Here What I have right now:

HTML

<button onclick="boldit()">B</button>
<div id="editor" contenteditable="true" class="email-body">
    This is an <strong>editable</strong> paragraph.
</div>

Javascript

function boldit(){
 document.execCommand('bold');
}
like image 765
Dasun Avatar asked Mar 28 '17 08:03

Dasun


2 Answers

The reliable way is to traverse the parent tree checking getComputedStyle.

I'll assume you have the selected element(s) already.

function isBold(_element) {
  var element = _element;
  while (element) {
    var style = getComputedStyle(element).fontWeight;
    if (Number(fontWeight) > 400 || fontWeight === 'bold' || fontWeight === 'bolder') {
      return true;
    }
    element = element.parentNode;
  }
  return false;
}
like image 74
Brigand Avatar answered Nov 20 '22 19:11

Brigand


jQuery(function($) {
    $('.embolden').click(function(){
        if(selectionIsBold()){
          alert('bold');
        }
        else {
          alert('not bold');
        }
    });
});

function selectionIsBold() {
    var isBold = false;
    if (document.queryCommandState) {
        isBold = document.queryCommandState("bold");
    }
    return isBold;
}
.bold {
    font-weight: bold;
}
<div contenteditable="true" class="textEditor">Some <span class="bold">random </span>text.</div>
<a href="#" class="embolden">Is Bold Text</a>
<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>

Highlight the text and click on the link.

like image 7
Kapila Perera Avatar answered Nov 20 '22 20:11

Kapila Perera