FoxyStyle
FoxyStyle

Reputation: 177

Drag an element to rotate it by specific °

http://codepen.io/kunokdev/pen/YXNrPx?editors=110

<div id="container">

  <div class="item-2"></div>
  <div class="item-2"></div>
  <div class="item-2"></div>
  <div class="item-2"></div>

</div>

body {
    background: #222;
}

#container {
 width: 300px;
 height: 300px;
 border-radius: 300px;
 background: #666;
 overflow: hidden;
}

.item-2 {
  float: left;
  background: blue;
  width: 50%;
  height: 150px;
 }
.item-2:nth-child(2){
  background: green;
 }
 .item-2:nth-child(3){
   background: yellow;
 }
.item-2:nth-child(4){
  background: red;
}

Check link first. So let's say I have that circle div. Now what I want is a simple function that will rotate it. If we drag-pull it to the right, it should rotate clockwise. And vice verse.

Upvotes: 0

Views: 77

Answers (1)

mpallansch
mpallansch

Reputation: 1194

I'm not sure if this solution would work on mobile or not, but this works for browsers: http://codepen.io/anon/pen/LVxzLj

var mouseX;
var currAngle = 0;
var container = document.getElementById("container");

container.addEventListener("mousedown",function(e){
  mouseX = e.pageX;
  window.addEventListener("mouseup",mouseup,false);
  window.addEventListener("mousemove",mousemove,false);
},false);

function mouseup(){
  currAngle = currAngle + e.pageX - mouseX;
  window.removeEventListener("mouseup",mouseup,false);
  window.removeEventListener("mousemove",mousemove,false);
}

function mousemove(e){
  var result = currAngle + e.pageX - mouseX;   
  container.style['transform'] = 'rotate(' + result + 'deg)';  
  container.style['-webkit-transform'] = 'rotate(' +  result + 'deg)';
  container.style['-moz-transform'] = 'rotate(' +  result + 'deg)';
}

Also, I added this css, because there were some odd behaviors with user selection

#container {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  user-select: none;
}

Upvotes: 1

Related Questions