Question

I have a textarea over a div. In the div I highlight certain parts of the text entered into the textarea. I'm trying to get mouse over events on the highlights but obviously I can't because they are under my textarea. I was thinking if this might be possible using mousemove events on the textarea to track the mouse coordinates but then I figured that that would do me no good as I can't determine the exact boundaries if the highlight spans.

my html setup

So the question is, how do I simulate mouseover and mouseout events for elements that do not receive these because they are under other element(s)?

EDIT:

I completed a workaround for this based on Marcus' answer. Full code for mouseover / mouseout events:

var mouseDown = false;
var mouseIsOver = false;
var lastOverElem = false;
textarea.mousemove(function(e) {
    if (!mouseDown) {
        textarea.hide();
        var elm = $(document.elementFromPoint(e.pageX, e.pageY));
        textarea.show();
        if (elm.hasClass("highlighted")) {
            /* MOUSE MOVE EVENT */
            if (!mouseIsOver) {
                mouseIsOver = true;
                /* MOUSE OVER EVENT */
            }
        } else {
            if (mouseIsOver) {
                mouseIsOver = false;
                if (lastOverElem) {
                    /* MOUSE OUT EVENT */
                }
            }
        }
    }
});

$('body').mousedown (function () {mouseDown = true;});
$('body').mouseup (function () {mouseDown = false;});
Was it helpful?

Solution

You can use document.elementFromPoint. Obviously this doesn't work if the textarea is in front of the underlying highlighting container, but there's an app for that. You just need to temporarily hide the textarea before calling document.elementFromPoint and then show it directly afterwards.

var textarea = $("#linksTextarea");
textarea.on("mousemove", function(e) {
    // Temporarily hide the textarea
    textarea.hide();
    // Get element under the cursor
    var elm = $(document.elementFromPoint(e.pageX, e.pageY));
    // Show the textarea again
    textarea.show();
    if (elm.hasClass("highlighted")) {
        console.log("You're mouse is over highlighted text");
    }
});

Since the DOM is updated in real-time while the rendering of it is delayed until after all of your JavaScript has been executed, you don't have to worry about any visual glitching.

See test case on jsFiddle.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top