Several sites like Quora's comment section have this, where you can control-b text inside a editable div, and it becomes bold, or you can control-b and whatever you type afterwards is bold until you do control-b again.

I've tried replicating this, and I have seen one question about how to do this with a button on Stack, but have had no success attempting this with shortcuts (control-B).

Here's my attempt mostly based off the other question I mentioned, but it isn't working:

JS

document.onkeyup = function(e) {
if (e.ctrlKey && e.which == 66) {
document.execCommand('bold');
};

HTML:

<div class="form-control" id="comment" contenteditable="true"></div>

I'm not very experienced when it comes to this usage of js, so I'm likely way off. Anyone have any ideo how this can be done?

1 Answers

0
Cybernetic On

You can enable bolding in editable divs as follows:

 // enable bolding

$(window).keydown(function(e) {

if (e.keyCode >= 65 && e.keyCode <= 90) {

    var char = (e.metaKey ? '⌘-' : '') + String.fromCharCode(e.keyCode)

    if (char == '⌘-B') {

        document.execCommand('bold')

    }

}

})