PHP User
PHP User

Reputation: 2422

how to create a popup next to the mouse according to a container div

I'm trying to display a div when mouse is over an element but the div is always inside the container div. Example (hover over any model at the bottom of this page) https://3dexport.com/ I've tried to get mouse position in the page and the mouse position inside the div but didn't work. Thanks in advance.

This is the main code I've used to display and hide a big div but the hidden process is not working though the alert is displayed (the black div is hidden by default)

$(".homeModelItem").mouseenter(function(){
var mouse = {x: 0, y: 0};

document.addEventListener('mousemove', function(e){
    mouse.x = e.clientX || e.pageX;
    mouse.y = e.clientY || e.pageY;
    console.log(mouse.x);
    if(mouse.x<400 && mouse.x>0){
        $(".black").css({"left":"200px","display":"block"});
    }

});
});

$(".homeModelItem").mouseout(function(){
alert("xxx");
$(".black").css({"display":"none","left":"0"});
});

Upvotes: 1

Views: 1262

Answers (1)

Teemu
Teemu

Reputation: 23396

You're adding a new mousemove listener every time the mouse enters a .homeModelItem. In that handler you set display: block for .black, and this will override the hiding in mouseleave handler.

It looks like you want to position .black related to the currently hovered .homeModelItem. You can do it for example like this:

$(".homeModelItem").mouseenter(function (e) {
    $(e.target).append($('.black')); // Move the .black to the target element
    $(".black").css({
        display: "block"
    });
});

$(".homeModelItem").mouseleave(function (e) {
    $(".black").css({
        display: "none"
    });
});

Addition to .homeModelItem CSS:

position: relative;

and to .black CSS:

left: 100px;
top: 0px;
z-index: 100;

A live demo at jsFiddle.

If you'll need the mousemove somewhere, you can add it, but outside of any event handler (unles you will remove it in another handler).

Upvotes: 1

Related Questions