I'm trying to build something like the highlight feature in Medium.
In the click event, I need to add an element that will be in a position: absolute to his parent where the user clicked (not the body since the parent is overflow: scroll;)
The issue is to add the mark element in the correct place.
- How can I find the top and left position of what the user highlighted?
- How can I add the marking relative to the article element? Whenever the user scrolls, I need the mark element to stay over the highlighted text.
I'm trying to set them with the below code;
mark.setAttribute("style", `top:${top}px`);
mark.setAttribute("style", `left:${left}px`);
https://codepen.io/nemo369/pen/ExjQgKy
const article =document.querySelector(`article`);
article.addEventListener('mouseup', function () {
var result = window.getSelection().toString();
const oldMark =document.querySelector(`.mark`);
if(oldMark){
article.removeChild(oldMark);
}
window.getSelection().empty()
if(result){
let mark = document.createElement('mark');
mark.innerText = `${result}`;
mark.classList.add('mark');
var top = 5;
var left = 15
mark.setAttribute("style", `top:${top}px`);
mark.setAttribute("style", `left:${left}px`);
article.appendChild(mark);
}
});
main{
display: flex;
flex-direction:column;
height:100vh;
align-items:center;
justify-content: center;
}
article{
max-height:30%;
overflow:scroll;
flex:0 0 50vw;
position: relative;
}
.mark{
position: absolute;
top:50%;
left:50%;
}
<main>
<article>
<p>I'm trying to build something like the highlight feature in Medium.<br>
The issue is that in the click event I need to add an element that will be in a <strong>position absolute</strong> to his parent and not the body since the parent is <strong>overflow: scroll;<strong><br>
How can I find those x and y conditions?
</p>
<p>I'm trying to build something like the highlight feature in Medium.<br>
The issue is that in the click event I need to add an element that will be in a <strong>position absolute</strong> to his parent and not the body since the parent is <strong>overflow: scroll;<strong><br>
How can I find those x and y conditions?
</p>
<p>I'm trying to build something like the highlight feature in Medium.<br>
The issue is that in the click event I need to add an element that will be in a <strong>position absolute</strong> to his parent and not the body since the parent is <strong>overflow: scroll;<strong><br>
How can I find those x and y conditions?
</p>
</article>
</main>
;