Reputation: 443
Say I have this text
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
and I want to make the bold
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
If I was to do this in Javascript
function myFunction(obj) {
var text1 = "Lorem ipsum ";
var text2 = "dolor sit amet";
var text3 = ", consectetur adipiscing elit.";
text2.bold();
obj.value = text1 + text2 + text3;
}
<textArea onmouseup=myFunction(this)>Lorem ipsum dolor sit amet, consectetur adipiscing elit</textArea>
I can't seem to bold the text, any ideas?
Upvotes: 3
Views: 9745
Reputation: 10081
As you can't style text inside a textarea
,
Here is a solution using a content-editable div
instead:
(Inspired by my solution to another question: Change font for selected text using JavaScript)
function changeStyle(style) {
var sel = window.getSelection(); // Gets selection
if (sel.rangeCount) {
// Creates a new element, and insert the selected text with the chosen style
var e = document.createElement('span');
e.classList.add(style.value); // Selected style (class)
e.innerHTML = sel.toString(); // Selected text
// https://developer.mozilla.org/en-US/docs/Web/API/Selection/getRangeAt
var range = sel.getRangeAt(0);
range.deleteContents(); // Deletes selected text…
range.insertNode(e); // … and inserts the new element at its place
}
}
.editable {
width: 360px;
height: 120px;
border: 1px solid #ccc
}
.editable .span-0{ /* Added to reset styles correctly */
font-weight: normal; /* Reset b */
text-decoration: none; /* Reset u */
font-style: normal; /* Reset i */
}
.editable .span-b{
font-weight: bold;
}
.editable .span-u{
text-decoration: underline;
}
.editable .span-i{
font-style: italic;
}
Highlight text and change style<br>
<select id="select_font" onchange="changeStyle(this);">
<option value="span-0" selected>None</option>
<option value="span-b">Bold</option>
<option value="span-u">Underlined</option>
<option value="span-i">Italic</option>
</select>
<div contenteditable="true" class="editable">
Some Content
</div>
(I added other styling options… just because!)
I hope it helps!
Upvotes: 6
Reputation: 65
For divs it would be done like this, however you can not include a span in a textArea, so if the textArea is necessary i cant really help
function myFunction(obj) {;
document.getElementById("span").style.fontWeight="bold";
}
<div onmouseup=myFunction(this) >Lorem ipsum <span id="span">dolor sit amet, </span> consectetur adipiscing elit</div>
Upvotes: 0
Reputation: 121
As far as I know, we can't style textarea and don't accept any HTML.
text2 = text2.bold()
will return dolor sit amet
but it will appear as text with b-tags.
Upvotes: 0
Reputation: 3742
The result should be stored like this:
function myFunction(obj) {;
var text1 = "Lorem ipsum ";
var text2 = "dolor sit amet"
var text3 = ", consectetur adipiscing elit.";
text2 = text2.bold();
obj.value = text1 + text2 + text3;
}
More info: https://www.w3schools.com/jsref/jsref_bold.asp
Upvotes: 0