Code Fingers
Code Fingers

Reputation: 301

How do I make text bold after the user clicks a button?

I am trying to make a text editor in JavaScript and it has various features like bolding the text and italics and some others. When the user clicks on any one of them, then anything that they have selected will become edited accordingly. Now I am able to get the selected text and even put strong tags before and after the text but when I do it the text doesn't get bold only the tags are seen. How can make the text bold? I sorry but I am unable to provide code since its too much and too messy. Thanks for reading query! Also if you know any JavaScript library which could help me solve this problem then you can suggest me.

document.getElementById("button").addEventListener("click",
  () => {
    let text = document.getElementById("text").innerText
    let selection = window.getSelection();
    let boldText = "<strong>" + selection + "</strong>"
    document.getElementById("text").innerText = text.replace(selection, boldText)
  })
<div id="text">
  The dog barks and runs around.
</div>
<button id="button">Make selected text bold</button>

I am using inner text instead of inner html in order to reproduce the problem

Upvotes: 0

Views: 1908

Answers (3)

Hetal Patel
Hetal Patel

Reputation: 1

<p id="mypar">Hello</p>
<br>
<button type="button" onclick="changeStyle()">Click Me</button>
<script>
function changeStyle(){
    var element = document.input
    var element = document.getElementById("mypar");
    element.style.fontWeight = "bold";
}
</script>

Upvotes: 0

user15786743
user15786743

Reputation:

You are using innerText to replace which is wrong as we want to change html so use innerHTML. Code:

document.getElementById("button").addEventListener("click",
  () => {
    let text = document.getElementById("text").innerText
    let selection = window.getSelection();
    let boldText = "<b>" + selection + "</b>"
    document.getElementById("text").innerHTML = text.replace(selection, boldText) //use innerhtml instead of innertext
  })
<div id="text">
  The dog barks and runs around.
</div>
<button id="button">Make selected text bold</button>

Upvotes: 3

Carter McKay
Carter McKay

Reputation: 490

Here is some code that I used to change to inputted text on a button click

<input type="text" id="sign" value="">
<p style = "font-family: 'Dancing Script', cursive; font-size:50px;" 
id="signOutput"></p>
<button onclick="signFunction()">Output Signature</button>

<script>

function signFunction() {var x = document.getElementById("sign").value;
         document.getElementById("signOutput").innerHTML = x;
         }

</script>

Upvotes: 0

Related Questions