0

I have a div which is editable and I am trying to format the text using buttons/anchors to trigger JQuery actions. The problem is that If I have a selected text inside the editable div and then if I click on #bold button to make it bold. The text loses focus and nothing happens to it.

HTML

<div class="poster">
    <div class="editor" contenteditable="true" placeholder="What's on your mind?"></div>

    <div class="posterButtons preventCollapse">
        <div class="pull-left">
            <a id="bold">B</a>
            <a id="italic">I</a>
            <a id="underline">U</a>
        </div>
        <div class="pull-right">
            <a class="submitPost">Post</a>
        </div>
    </div>
</div>

JQuery

$('#bold').click(function(){
    document.execCommand('bold', false);
});
Community
  • 1
  • 1
Feelsbadman
  • 1,163
  • 4
  • 17
  • 37

2 Answers2

1

you can use <button> instead of <a>

$('#bold').click(function(){
    document.execCommand('bold', false);
});
.editor {

    height: 100px;
    border: 1px solid #ddd;
    padding: 10px;
    outline: none;

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="poster">
    <div class="editor" contenteditable="true" placeholder="What's on your mind?"></div>

    <div class="posterButtons preventCollapse">
        <div class="pull-left">
            <button type="button" id="bold">B</button>
            <button type="button" id="italic">I</button>
            <button type="button" id="underline">U</button>
        </div>
        <div class="pull-right">
            <a class="submitPost">Post</a>
        </div>
    </div>
</div>

you can read Why getting a text selection from textarea works when a button clicked but not when a "div" clicked (in Internet Explorer)

Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28
1

Please use <button type="button" id="bold">B</button> instead of <a id="bold">B</a>. Only use <a> tag if you have to redirect or something like that.

Also, if you are using a button as a submit button try to use <button type="submit" id="bold">B</button>. The difference is button type is just a button or submit button.

Sushil
  • 1,111
  • 1
  • 10
  • 23