I have an HTML5 file and I am trying to make an app like Google Docs using create-electron-app.
I have a textarea tag for the input, and I am trying to bold the text the user has selected. I have the getSelectedText() function working and It is returning a string like expected, but I need to bold that text inside of the textarea. If you have used Google Docs you should know what I mean.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Make word documents!</title>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<textarea ></textarea>
<input type="button"
value="Bold"
onm ousedown="bold()">
<script>
function getSelectedText() {
if (window.getSelection) {
return "" window.getSelection();
} else if (document.selection && document.selection.type == "Text") {
return document.selection.createRange().text;
}
return "";
}
function bold() {
var userInput = getSelectedText();
// userInput.style.fontWeight = "bold";
// print the type of the userinput variable
console.log(typeof userInput);
}
</script>
</body>
</html>
CodePudding user response:
It isn't possible to bold text inside of a textarea, however, it is possible to bold text inside of a div.
A div can behave like a textarea by setting it to contentEditable -- <div contentEditable></div>
.
Conveniently, Javascript has a built in function to bold selected text, document.execCommand("bold")
.
By using both editable divs and Javascript built in functions, it is possible to create an app like Google Docs that can bold selected text.
document.getElementById("bold_button").onclick = function() {
document.execCommand("bold");
}
<div contentEditable id="text">
The World Before the Flood is an oil-on-canvas painting by English artist William Etty, first exhibited in 1828. It depicts a scene from John Milton's Paradise Lost in which Adam sees a vision of the world immediately before the Great Flood. The painting illustrates the stages of courtship as described by Milton: a group of men select wives from a group of dancing women, take their chosen woman from the group, and settle down to married life. Behind them looms an oncoming storm, a symbol of the destruction which the dancers and lovers are about to bring upon themselves. When first exhibited at the 1828 Royal Academy Summer Exhibition, the painting attracted large crowds. Many critics praised it, but others condemned it as crude, tasteless and poorly executed. The painting, currently in the Southampton City Art Gallery, and a preliminary oil sketch for it, now in the York Art Gallery, were exhibited together in a major retrospective of Etty's work in 2011 and 2012
</div>
<button id="bold_button">Bold</button>