Assuming something selected
var selection = window.getSelection(),
rect now an object that holds positions relative to the current scroll position of the window. Read more about it here . If you want to be more precise, you can use getClientRects , which returns a list of such objects that you would need to put together to form a selection.
Now, to draw a window around it (I will use a simple route, using fixed for demonstration)
var div = document.createElement('div'); // make box div.style.border = '2px solid black'; // with outline div.style.position = 'fixed'; // fixed positioning = easy mode div.style.top = rect.top + 'px'; // set coordinates div.style.left = rect.left + 'px'; div.style.height = rect.height + 'px'; // and size div.style.width = rect.width + 'px'; document.body.appendChild(div); // finally append
You will probably want to take into account the scroll position so that you can use absolute positioning. If there are no other scrollable elements, this means that you just need to consider the values ββof window.scrollX and window.scrollY , which are the position of the x and y window coordinates in pixels at the moment they are accessed.
var div = null; function drawBorderAroundSelection() { var selection = window.getSelection(),
<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ut dolor porta neque vulputate auctor et a ligula. Quisque bibendum risus magna, eget feugiat erat faucibus sed. Phasellus sed massa elementum, laoreet ipsum non, dignissim orci. Aenean lobortis nunc et purus molestie, vel consectetur ligula dapibus. In ut lorem mattis, commodo nisi aliquam, porta ante. Curabitur sit amet libero sed justo finibus porttitor. Donec ac est ultrices, pretium diam sed, blandit nunc. Morbi consequat finibus augue vel ultricies. Vestibulum efficitur ante vitae cursus accumsan. Vestibulum rutrum ex ex, a egestas nisi malesuada eu. Pellentesque fermentum, ante id convallis luctus, tellus lectus viverra diam, sit amet convallis ligula lorem sit amet neque. </p>
source share