Search code examples
jqueryimagebackgroundslide

jQuery - Moving background arrow in menu


I would expect something like this to be pretty popular in demand but I had much trouble finding a suiting script.

I've got a basic menu build like this:

<div id="menu">
    <ul>
        <li><a href="#"><img src="images/btn1.png"></a></li>
        <li><a href="#"><img src="images/btn2.png"></a></li>
        <li><a href="#"><img src="images/btn3.png"></a></li>
    </ul>
</div>

The div #menu has a background image of a small arrow. I want the arrow to move vertically in front of the corresponding menu image when you mouseover/mousemove the whole #menu div.

Also when one of the menu images has been clicked the arrow should stay in it's position in front of the corresponding menu image.

I started something but I notice it's going downwards, since it's only working when you're at the top of the page. What I have is this:

$('#menu').css({backgroundPosition: '5px 10px'}); //Starting position

$('#menu').mousemove(function(e){
    $('#menu').stop().animate(
        {backgroundPosition: '5px ' + (e.pageY-60) + ' px'},
        {duration:100}
    )
}).mouseout(function(){
    $('#menu').stop().animate(
        {backgroundPosition: '5px 10px'},
        {duration:100}
    )
});

Please help!

ps. I'm using this plugin to move background images smoothly.


Solution

  • After some math I managed to work it out. Later on I found someone who managed to do it even faster:

    function rPosition(elementID, mouseX, mouseY) {
      var offset = $('#'+elementID).offset();
      var x = mouseX - offset.left;
      var y = mouseY - offset.top;
    
      return {'x': x, 'y': y};
    }
    

    Source