How can I add a style="background-color: aqua" as a highlight in the textarea just to the word coming from the list above after a click. Here my html:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<ul id="box">
<li>Add</li>
<li>Sum</li>
<li>Div</li>
<li>Text4</li>
<li>Text5</li>
</ul>
<textarea rows="4" cols="50" id="id-of-your-textarea"></textarea>
</body>
Here my script:
<script>
const textArea = document.getElementById('id-of-your-textarea');
const boxLi= document.getElementById('box').children;
for(let i = 0; i < boxLi.length; i ){
boxLi[i].addEventListener('click', () => {
textArea.value =boxLi[i].textContent;
})
}
</script>
CodePudding user response:
const textArea = document.getElementById('id-of-your-textarea');
const boxLi = document.getElementById('box').children;
for (let i = 0; i < boxLi.length; i ) {
boxLi[i].addEventListener('click', () => {
$(boxLi[i]).addClass('highlight');
// remove the highlight from siblings
$(boxLi[i]).siblings().removeClass('highlight');
textArea.value = boxLi[i].textContent;
})
}
.highlight {
background-color: aqua;
}
<ul id="box">
<li>Add</li>
<li>Sum</li>
<li>Div</li>
<li>Text4</li>
<li>Text5</li>
</ul>
<textarea rows="4" cols="50" id="id-of-your-textarea"></textarea>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
CodePudding user response:
The TextArea Only contains the text content so styling the textarea content is not possible, Instead, you can use a element, and there the text you enter can be highlighted.
Try this
<!doctype html>
<html lang="en">
<head>
<style>
.background{
height:100px;
width:500px;
border:2px solid black;
}
</style>
</head>
<body>
<ul id="box">
<li>Add</li>
<li>Sum</li>
<li>Div</li>
<li>Text4</li>
<li>Text5</li>
</ul>
<div id="id-of-your-textarea" contenteditable>
This is a Sum Add For the Text4 any random text
</div>
</body>
<script>
const textArea = document.getElementById('id-of-your-textarea');
const boxLi= document.getElementById('box').children;
function highlighter(e)
{
let text = e.target.textContent;
let innerText = textArea.textContent;
if(innerText) {
textArea.innerHTML = innerText.replace(text, `<span style="background-color:aqua;">${text}</span>`)
}
}
for(list of boxLi)
{
list.addEventListener('click', highlighter)
}
</script>
</html>