Jquery draggable moves only 30 degrees

I want to have a selector that moves around the bar at an angle of 30 degrees, I did some research on the Internet, but I did not find any solution !.

I know that:

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

will move it along the x axis and:

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

will move it along the y axis, but the question is, how to move it only at an angle of 30 degrees?

enter image description here

I want this menu to work.

enter image description here

+8
javascript jquery jquery-ui-draggable
source share
1 answer

This is actually pretty easy!
All you have to do is control the position of your element in the drag event, and a little trigonometry will do the hard work for you ...


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


 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> 
+5
source share

All Articles