I am trying to highlight individual spans inside my document body onmouseup. My trouble is that for some reason every element is highlighted by default and I can't seem to get it to work on window.getSelection(). I only need it to highlight the span when I've clicked it.
Would anyone know a quick way of doing this?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>The HTML5 Herald</title>
<meta name="description" content="The HTML5 Herald">
<meta name="author" content="SitePoint">
<link rel="stylesheet" href="./styles.css">
</head>
<body>
<h2>doc body</h2>
<div id="docbod" class="docbody"> </div>
<script src="./highlight.js"></script>
</body>
</html>
var documentbody = document.getElementById("docbod");
/* turns every word in the document into an element then appends them to the div that contains the doc body */
function splitdocintowords(div) {
var divarray = []
var state = ["hey", "there", "how", "are", "you", "doing?"]
for (let i = 0; i < state.length; i++) {
span = document.createElement("span")
span.textContent = state[i]
//-------^
span.id = "word" + i;
span.classList.add("textBackground")
span.addEventListener("onMouseup", highlight(span));
div.append(span);
div.append(" ");
}
}
splitdocintowords(documentbody);
/* highlights a selected word within the document*/
function highlight (element){
element.style.background='yellow';
console.log("selected element")
}