Search code examples
javascriptjquerymouseovermouseoutbounding-box

storing mouse position as variable and comparing with values to fire events


I'm in a position where I can't simply use a hover event, but I need to trigger mouseover and mouseout when the mouse is inside the area of a given element and when it leaves that area. It can be javascript, or jquery, or a mix. I haven't successfully been able to store the mouse positions as variables or figure out a way to tell when the mouse leaves the given area. My questions are each represented by '????' in the code.

function targetMouse() {
    var box = document.getElementById('CleanBox'),
        top = box.offsetTop,
        left = box.offsetLeft,
        right = left + box.offsetWidth,
        bottom = top + box.offsetHeight,
        mouseX = ????;
        mouseY = ????;

    if (left < mouseX > right && top < mouseY > bottom) {
        $('#CleanBox').mouseover();
    }
    else if (????) {
        $('#CleanBox').mouseout();
    }
}

thanks for the help!


Solution

  • Something like this?

    .box {

        width:300px;
        height:100px;
        position: absolute;
        top: 30%;
        left: 30%;
        background-color:yellow;
        border:2px solid;
    }
    
    <div id="popup">Mouse is on box</div>
    <div id="box" class="box"></div>
    
    var box = document.getElementById("box");
    var top = box.offsetTop;
    var left = box.offsetLeft;
    var right = left + box.offsetWidth;
    var bottom = top + box.offsetHeight;
    var hoverState = false;
    var popup = document.getElementById("popup");
    
    popup.hidden = true;
    
    function hoverCheck(evt) {
        var x = evt.clientX;
        var y = evt.clientY;
    
        if (x >= left && x <= right && y >= top && y <= bottom) {
            if (hoverState === false) {
                hoverState = true;
                console.log("mouseon");
            }
        } else {
            if (hoverState === true) {
                hoverState = false;
                console.log("mouseoff");
            }
        }
    
        popup.hidden = !hoverState;
    }
    
    document.addEventListener("mousemove", hoverCheck, false);
    

    on jsfiddle