HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Simple jQuery drag event

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
dragsimplejqueryevent

Problem

I would like some comments on my code and implementation for this simple piece of jQuery.

Basically it is 2 div boxes #side1 and #side2, in a container div called #frontimage, where #side2 can be swung out by dragging from right to left along #frontimage.

My jQuery code below continuously updates the CSS transform rotateY parameters for #side2 based on a mousemove event.

Here is a working example:

http://jsfiddle.net/Sr4zw/embedded/result/

And here is the complete code including HTML and CSS:

http://jsfiddle.net/Sr4zw/

$(document).ready(function() {

    var yDegrees = 0, slidingLength = 372, maxRotation = -45;

    $("#frontimage").on('mousedown', function( event ) {

        var originX = event.pageX;

        $("#frontimage").on("mousemove", function( event ) {

            yDegrees = yDegrees + (((originX - event.pageX) / slidingLength) * maxRotation);
            if (yDegrees  0) {
                yDegrees = 0;
                };

            originX = event.pageX;

            $("#side2").css({
                '-webkit-transform': 'rotateY(' + yDegrees + 'deg)',
                '-moz-transform': 'rotateY(' + yDegrees + 'deg)',
                '-ms-transform': 'rotateY(' + yDegrees + 'deg)',
                '-o-transform': 'rotateY(' + yDegrees + 'deg)',
                'transform': 'rotateY(' + yDegrees + 'deg)'
            });
        });
    });

    $('html').on('mouseup', function() {

        $("#frontimage").off('mousemove');

    });
});


Some comments on my implementation:

yDegrees stores the current rotation degree.
slidingLength is the length (in pixels) of the mouse drag that changes yDegrees.

Solution

The semicolons after the closing braces are really unnecessary, and the indentation is a bit off here:

if (yDegrees  0) {
            yDegrees = 0;
            };


It would be better this way:

if (yDegrees  0) {
            yDegrees = 0;
        }


This could be written more compactly:

yDegrees = yDegrees + (((originX - event.pageX) / slidingLength) * maxRotation);


Like this:

yDegrees += (originX - event.pageX) / slidingLength * maxRotation;


That is, using += and removing unnecessary parentheses.

Code Snippets

if (yDegrees < maxRotation) {
            yDegrees = maxRotation;
        };
        if (yDegrees > 0) {
            yDegrees = 0;
            };
if (yDegrees < maxRotation) {
            yDegrees = maxRotation;
        }
        if (yDegrees > 0) {
            yDegrees = 0;
        }
yDegrees = yDegrees + (((originX - event.pageX) / slidingLength) * maxRotation);
yDegrees += (originX - event.pageX) / slidingLength * maxRotation;

Context

StackExchange Code Review Q#35609, answer score: 6

Revisions (0)

No revisions yet.