I would like to allow editing of text when actual text is clicked. The rest of the white space I need for a dragging functionality.
Is there any way to detect when mouse clicks on text instead of white space in a contenteditable div?
Is there maybe some CSS I can add to a div that would wrap around the text and not the whitespace? Or is there some Javascript that can tell when user clicked on text.
<div >
<div contenteditable="true"></div>
</div>
.container{
min-width: 100px;
width: min-content;
height: min-content;
padding: 10px;
border: 1px solid black;
}
.textbox{
min-width: 100px;
width: min-content;
}
CodePudding user response:
One solution would be to insert each text in a <p>
tag. The <p>
will extend on the whole with of the container. Inside <p>
, i would wrap each part of text in a <span>
tag. So whenever the users clicks on the text, the target of the event would be the span element, and when the users clicks on the whitespace, the target of the event would be a p element.
document.querySelector(".container").addEventListener("click", function(event){
if(e.target.localName == "p") {
//whitespace
}
if(e.target.localName == "span") {
//text
}
});
CodePudding user response:
I don't think you can check if someone clicked on the empty space of an element.
The best way to do this is to create div as the border of the textbox and check with javascript if the user clicked on the border.
document.getElementById("drag-border").addEventListener("click",function(event){
//This if blocks calling rest of function when user clicks on textbox and not on border
if (event.currentTarget !== event.target) {
return;
}
console.log( "Clicked on border" );
});
.container{
min-width: 100px;
width: min-content;
height: min-content;
}
.textbox{
min-width: 100px;
width: min-content;
border: 1px solid black;
background: white;
}
#drag-border{
background: red;
padding: 10px;
border: 1px solid black;
}
<div >
<div id="drag-border">
<div contenteditable="true"></div>
</div>
</div>