Reputation: 89
This seems like a trivial thing to do, but for some reason I cannot make it work.
I'm trying to highlight text inside a contenteditable div tag, using the execCommand. However, I can't use the "hiliteColor" argument, since I also want to add an onclick event to the span tag (to be able to remove the highlight again). So here's what the function looks like:
export function highlight(color){
//remove any format to avoid overlap issues
document.execCommand('removeFormat', false, null);
//save selected text
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
//create new span around the text
var span = document.createElement("span");
span.style.backgroundColor = color;
span.onclick = doSomething(); // <-------------------------------- ISSUE
span.innerText = text;
document.execCommand('insertHTML', false, span.outerHTML);
}
function doSomething(){
alert('I was clicked!');
}
I tried adding the functions in several ways, including span.addEventListener('click', () => alert('test'));
, but the onclick is never added to the span tag. Adding the style on the line above works fine.
I'm doing this in a React application if that matters.
How can I attach a function to this span? Or is there a completely different way to do the highlighting?
Thank you.
Upvotes: 0
Views: 2683
Reputation: 1661
If you are using React
i would suggest using the React
to create and ReactDOM
to render the element. you would import ReactDOM
in your component like
import ReactDOM from "react-dom";
and then you can create and render the element
let SpanElement = React.createElement(
"span",
{
style: { backgroundColor: "#0099FF"}, //Color Here
id: "SpanID",
className: "SpanClassName",
onClick: () => doSomething()
},text);
// First Argument element to Render, Second Argument: Node to Render at
ReactDOM.render(SpanElement, document.getElementById("root"));
Upvotes: 1
Reputation: 625
I suspect text inside span
tag is an empty string
// CASE 1
let hasText = document.createElement("span")
hasText.innerText = "I am span element"
hasText.onclick = () => console.log("clicked - text")
hasText.style.background = `red`
document.body.appendChild(hasText)
// CASE 2
let noText = document.createElement("span")
noText.onclick = () => console.log("clicked - no text")
noText.style.border = `green`
document.body.appendChild(noText)
Upvotes: 0