0

I want to achieve something similar to this, but the X would not be aligned with js and I don't think there's a way to calculate the text's position to center the X. enter image description here

I tried also ::selection::after { content: '☓'; }, this is not working either.

Here is my code example. I attached the event on the right click, on opening context menu.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <div>
        Lorem ipsum dolor sit amet consectetur adipisicing elit.
    </div>
    <div class="X" style="background-color: red; width: 12px;">&#x2613;</div>
    <script type="text/javascript">
        document.oncontextmenu = function(e) {
            const xElement = document.querySelector('.X');
            const styleValue = 'position: fixed; background-color: red; width: 12px; ' + 'top: ' + e.y +'px; ' + 'left: ' + e.x +'px;'; 
            xElement.setAttribute("style", styleValue);
        }
    </script>
</body>
</html>
meightythree
  • 308
  • 2
  • 16

1 Answers1

0

I believe you want to create a custom context menu, it's one of the ways which can be done in order to do that, but there are other edge cases which you need to consider.
Because selecting text can happen using the keyboard as well, you may need to also add the same event listener for keyup event as well.

const el = document.querySelector(".x");

function getSelectedText() {
    var text = "";
    if (typeof window.getSelection != "undefined") {
        text = window.getSelection().toString();
    } else if (
        typeof document.selection != "undefined" &&
        document.selection.type == "Text"
    ) {
        text = document.selection.createRange().text;
    }
    return text;
}

document.addEventListener("mouseup", (event) => {
    var selectedText = getSelectedText();
    if (selectedText) {
        el.classList.add("active");
        el.style.left = event.pageX + "px";
        el.style.top = event.pageY + "px";
    } else {
        el.classList.remove("active");
    }
});
.x {
    background-color: red;
    width: 12px;
    position: fixed;
    top: 0;
    right: 0;
    visibility: hidden;
    opacity: 0;
}

.x.active {
    visibility: visible;
    opacity: 1;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>
    <div>
        Lorem ipsum dolor sit amet consectetur adipisicing elit.
    </div>
    <div class="x">&#x2613;</div>
</body>

</html>
M.A Shahbazi
  • 876
  • 9
  • 23
  • If go from right to left, the X will end up on the left side, but I think I can build up on your answer, with tracking mouse down also and then calculating which will be the "end" selection. Thanks! – meightythree Mar 20 '22 at 12:49