0

I would like to have a circular div on my webpage and to be able to spin it as if it were like a wheel of fortune using the mouse. I have tried to use jQuery drag, but I couldn't figure out a way to rotate the div.

Is there a way to rotate div elements using the mouse? Also what would be cool is if it were possible to add momentum?

Shrey Gupta
  • 5,509
  • 8
  • 45
  • 71
  • 1
    possible duplicate of [Rotating a Div Element in jQuery](http://stackoverflow.com/questions/382591/rotating-a-div-element-in-jquery) – Khamidulla Dec 27 '13 at 00:20
  • You should check this jQuery plugin that can rotate elements: https://code.google.com/p/jqueryrotate/ It has good cross-browser support. You could do it with CSS3, but it wouldnt have good browser support. Once you know how to rotate elements with this plugin, take a look at http://stackoverflow.com/questions/4127118/can-you-detect-dragging-in-jquery . This will give you and idea of what to do next. – gskema Dec 27 '13 at 00:32

1 Answers1

2

You can actually do this without ANY Javascript or jQuery by taking advantage of the magic of CSS3 Transitions and Transforms.

First, you need to set your div to have a rotation of zero degrees by setting the transform attribute like so:

div {
    transform:rotate(0deg);
}

Then, you just need the hover-based transition (aka, the spin effect). To do that, you can use the :hover pseudo element, like so:

div:hover {
    transition: transform 1s ease;
    transform: rotate(360deg);
}

If you would like the element to have a transition where it spins back in place, simply add the transition attribute to the CSS for div, like so:

div {
    transform:rotate(0deg);
    transition: transform 1s ease;
}

Of course, the timing of 1s is totally up to you; feel free to use any value you want, even ms (for milliseconds).

Here's some more information on CSS3 Transitions and Transforms:

And here's an example of this kind of rotation in action: http://www.w3schools.com/css/tryit.asp?filename=trycss3_transition2.

As for compatibility, it is supported by about 76% of the average browser market: http://caniuse.com/#search=transitions

Note that some browsers don't support the transition property as is; some require you to use a vendor prefix for support. For example, Chrome and Safari have the prefix -webkit-, so you would put -webkit-transition: transform 1s ease; to make it work in those browsers. I have listed the vendor prefixes below:

  • Chrome/Safari: -webkit-
  • Opera: -o-
  • Firefox: -moz-
  • Internet Explorer: -ms-
Shrey Gupta
  • 5,509
  • 8
  • 45
  • 71