Reputation:
I want to change the font when I highlight a text in the textarea. The function below changes the whole font in the textarea, rather than the text I want to change.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>E-commerce Website</title>
<script>
function selectFont() {
document.getElementById("note_header").style.fontFamily = "cursive";
}
</script>
</head>
<body>
<select id="select_font" onchange="selectFont()">
<option>Select a font</option>
<option>Cursive</option>
</select>
<textarea id="note_header">Title</textarea>
</body>
</html>
Upvotes: 2
Views: 368
Reputation: 48
Changing font of text within the Textarea won't work but will work for other properties like color, cursor etc.
A workaround is to use a content editable <div>
. You can get the selected text with window.getSelection
and then wrap with a <span>
, after you can apply the style to span's content. As shown below.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>E-commerce Website</title>
<script>
function selectFont() {
selectedText = window.getSelection().toString();
NoteHeader = document.getElementById("note_header");
EditedText = NoteHeader.innerText.replace(selectedText,
`<span style="font-family: cursive">${selectedText} </span>`);
NoteHeader.innerHTML = EditedText;
}
</script>
</head>
<body>
Highlight text and change font <br>
<select id="select_font" onchange="selectFont()">
<option>Select a font</option>
<option>Cursive</option>
</select>
<div contenteditable="true" id="note_header"
style="width:200px; height:200px; border: 1px solid #ccc">
Some Content
</div>
</body>
</html>
Upvotes: 2
Reputation: 7346
There is no direct way to achieve your goal, but you could use the CSS pseudo element ::selection
to give the selected text some properties. Sadly the font-family
can't be changed with this, but if you only want to highlight it in some way the properties you can change are:
#note_header::selection {
color: red;
background: #eee;
}
<textarea id="note_header">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.</textarea>
Upvotes: 2