0

I have a red div with green child, the green one moves when mouse hovers over it's parent. Pretty simple.

HTML:

<div class="big">
    <div class="small"></div>
</div>

CSS:

.big {
    position: relative;
    width: 200px; height: 200px;
    margin: 20px auto;
    background: red;
}

.big:hover .small {
    opacity: 1;
}

.small {
    position: absolute;
    top: 0; left: 0;
    width: 50px; height: 50px;
    background: green;
    opacity: 0;
}

JavaScript:

$('.big').on('mousemove', function (e) {

    var $this = $(this),
        small = $this.find('.small'),
        offset = $this.offset(),
        cursorX = e.pageX - offset.left,
        cursorY = e.pageY - offset.top,
        smallX = cursorX - small.width() / 2,
        smallY = cursorY - small.height() / 2;

    $('.small').css({
        top: smallY,
        left: smallX
    });

});

How to make the green box to disappear when it leaves the red one? :hover in css doesn't work because green div is part of the red one (I quess), so cursor never actually leaves it. Only when you move themouse really quickly the green div can't keep up with the cursor and disappers. Perhaps adding some wrapper elements with specific positioning will do the trick? Or something like jQuery stopPropagation()?

Here's my Fiddle

UPDATE: Here's updated code, based on suggestions from user nevermind. I added a transition, it disappears as I wanted it to, but now there's other problem. When cursor is moved outside the red box quickly, the green box stays at the border of it's parent.

Robert Kirsz
  • 1,257
  • 1
  • 13
  • 15

2 Answers2

1

I think this is what you want:

http://jsbin.com/obewaz/1/

http://jsbin.com/obewaz/1/edit

Same html/css, few additions in jquery:

$(document).ready(function() {

$('.big').on('mousemove', function (e) {



    var $this = $(this),
        smalle = $this.find('.small'),
        offset = $this.offset(),
        position=smalle.position(),
        cursorX = e.pageX - offset.left,
        cursorY = e.pageY - offset.top,
        smallX = cursorX - smalle.width() / 2,
        smallY = cursorY - smalle.height() / 2;

    $('.small').css({
        top: smallY,
       left: smallX
    });

console.log(position);   

if(position.left<0 || position.left>150 || position.top<0 || position.top>150) {
    $('.small').css('display','none');
}
else {

$('.small').css('display','block');
}


});
});

Of course, you can change/tweak values in last condition a little to fit your needs. Idea is: track position of small box, and when it is 'outside' of big box - hide it.

sinisake
  • 11,240
  • 2
  • 19
  • 27
  • I was thinking about something like this, I'll try to update my code and maybe add some opacity transition, because that'll be in final project. – Robert Kirsz Jun 25 '13 at 17:48
0

instead of mousemove try mouseover

DEMO

Aravind30790
  • 974
  • 9
  • 22