Move element over element where cursor is

Asked

Viewed 146 times

1

I have this code: I wanted '#hoverLayer' to move (Animate) to one of '#bts' ('#bt1','#bt2','#bt3','#bt4'), depending on where the cursor is. Any idea?

html:

<div id="bts">
    <div id="hoverLayer"></div>
    <div id="bt1"></div>
    <div id="bt2"></div>
    <div id="bt3"></div>
    <div id="bt4"></div>
</div>

css:

#hoverLayer {
    display: block;
    width: 155px;
    height: 50px;
    border: 2px solid green;
    position: absolute;
}
#bts {
    display: block;
    width: 620px;
    height: 50px;
    font-size: 0;
    position: absolute;
    z-index: 2;
    top: 30px;
    right: 0;
    cursor: pointer;
    left: 0;
    margin: auto;
}
#bt1, #bt2, #bt3, #bt4 {
    width: 155px;
    height: 100%;
    display: inline-block;
}

Js: this is what I’ve done so far, grab the id of the element that is Hover... just need to grab its location (I have no idea how) and give the '#hoverLayer' the same.

$('#bts div[id^="bt"]').mouseenter(function() {
    alert($(this).attr('id'));
})
  • Create a Jsfiddle

  • http://jsfiddle.net/mesh18av/1/

2 answers

1


You can achieve your goal as follows:

Example in Jsfiddle

$('#bts > div:not("#hoverLayer")').on('mouseenter', function() {
    $target = $(this);
    $('#hoverLayer').css({"left":$target.position().left});
});

Explanation

When the cursor is in the widget #bts over a child element that is not the #hoverLayer, we assign the definition of CSS left of the element where the mouse is to the element we want to move.

  • Thank you, I made an arrangement (http://jsfiddle.net/mesh18av/3/) but it was this (position()) that was missing... Obgado

0

Offset example()

    $('#bts div[id^="bt"]').mouseenter(function() {
      var offset = $( this ).offset();
      $("#hoverLayer").offset({ top: offset.top, left: offset.left });
    })

Browser other questions tagged

You are not signed in. Login or sign up in order to post.