Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery draggable moves on 30 degrees only

I want to have a selector that moves on a bar on 30 Degree angle , I have done some research on the web but I couldn't find any solution!.

I know that :

$( ".selector" ).draggable({ axis: 'x' });

will move it on x axis and :

$( ".selector" ).draggable({ axis: 'y' });

will move it on y axis but the question is how to move it on 30 degree angle only ?

enter image description here

I want to make this menu work .

enter image description here

like image 910
Madian Malfi Avatar asked May 27 '15 15:05

Madian Malfi


1 Answers

In fact, it's pretty easy!
All you have to do is control the position of your element in the drag event, and a bit of trigonometry will do the hard-work for you...


Edited:
Here is the original answer
Here is the new one


var rad = Math.PI / 180;

$("#Handle").draggable(
{
    drag: function(event, ui)
    {
        var offset =
        {
            x: ui.offset.left - ui.originalPosition.left,
            y: ui.offset.top - ui.originalPosition.top
        };
        
        var distance = Math.sqrt(offset.x * offset.x + offset.y * offset.y);
        distance = Math.min(distance, 150);
        
        var angle;
        
             if (offset.y > 0) { angle = 90 * rad; } // Moving downwards
        else if (offset.x < 0) { angle = 210 * rad; } // Moving leftwards
        else                   { angle = 330 * rad; } // Moving rightwards
        
        ui.position.top = Math.sin(angle) * distance + ui.originalPosition.top;
        ui.position.left = Math.cos(angle) * distance + ui.originalPosition.left;
    }
});
body { margin: 0; }
#Handle
{
    top: 150px;
    left: 200px;
    width: 25px;
    height: 25px;
    background-color: red;
}

#Background
{
    position: absolute;
    top: 150px;
    left: 200px;
}

#Background .bottom,
#Background .left,
#Background .right
{
    transform-origin: top left;
    width: 150px;
    height: 1px;
    background-color: blue;
}

#Background .bottom { transform: rotate(90deg); }
#Background .left { transform: rotate(210deg); }
#Background .right { transform: rotate(330deg); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

<div id="Background">
    <div class="right"></div>
    <div class="bottom"></div>
    <div class="left"></div>
</div>

<div id="Handle"></div>
like image 111
NemoStein Avatar answered Oct 12 '22 17:10

NemoStein