I am formatting a document for printing and I need to add a page break + header and footer in certain coordinates, if the coordinate is in the middle of the paragraph I need to divide it. I can already do the inserts by manually entering the position where the paragraph divides.
In my initial approach I tried to get the word in the (x, y) coordinate and then the indexOf()
of that word in relation to the paragraph. With "index" I can integrate with existing code.
The closest I got was to use the document.elementFromPoint(x,y)
function, which returns the entire paragraph.
Below the test code. I'm using the click event of the mouse to simulate the coordinates. In my implementation, only calculated coordinates will be used.
document.addEventListener('click', function(event) {
alert(document.elementFromPoint(event.clientX, event.clientY).textContent);
}, false);
div {margin: 15px 0;}
p {margin: 0;}
<div>
<p>Cras vel erat sit amet eros posuere volutpat nec in massa. Quisque dignissim mollis aliquet.</p>
<p>Fusce suscipit rhoncus mi a dapibus. Donec nisl augue, molestie sed porttitor id, pulvinar tempor neque.</p>
<p>Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec et enim eleifend velit faucibus consequat vel at risus.</p>
</div>
<div>
<p>Aliquam erat volutpat.</p>
<p>Phasellus ornare feugiat convallis. Aenean tincidunt tristique sem eu porttitor. Aliquam convallis eu purus et venenatis.</p>
<p>Suspendisse euismod ullamcorper odio, ac sollicitudin quam pharetra sed. Vestibulum dictum cursus sollicitudin.</p>
<p>Praesent at odio nisi. Interdum et malesuada fames ac ante ipsum primis in faucibus. Mauris sodales vehicula neque quis imperdiet. Morbi lacinia libero in posuere porttitor. Curabitur pretium vel tortor in aliquet.</p>
</div>
<div>
<p>Integer eu sapien odio. Morbi blandit nibh leo, in dapibus sem malesuada vitae. Etiam sit amet tristique sem.</p>
<p>Sed mattis lectus lorem, at dapibus leo suscipit quis. Nunc in massa quis mauris suscipit gravida. Sed at nunc mauris. Duis et lectus ex.</p>
</div>