SGS Venkatesh SGS Venkatesh - 4 months ago 7
jQuery Question

Changing -webkit-transform using jQuery not working as expected

I have made a simple jQuery script to create a line and make it move along with cursor. Find its fiddle here.

This is how I am assigning the slope

$("#line").css({
"width": + width +"px",
"height": "4px",
"-webkit-transform": "rotate(" + slope + "deg)",
"-moz-transform": "rotate(" + slope + "deg)"
});


The line is flickering in Chrome and not working in Firefox. What could be the reason for this?

Answer

Although as pointed out it is advisable to use transform without vendor prefixes (because jQuery automagically adds vendor prefixes for you), that is not the source of the problem. I realized that using event.offsetX and event.offsetY is giving conflicting values that constantly flips between positive and negative values upon mousemove, causing the slope calculation to be borked (thus flickering).

I have created a fork of your fiddle to demonstrate how offsetX/Y and clientX/Y measurements are different, and why using the latter is preferable:

Instead, use the .clientX and .clientY objects instead:

$(document).bind("mousemove", function(event) {
    if (getClickStarted){

        if (event && event.preventDefault){
            event.preventDefault();
        }

        // Use clientX/Y instead of offsetX/Y
        curX = event.clientX;
        curY = event.clientY;

        var width = Math.sqrt(Math.pow(curX - centerX, 2) + Math.pow(curY - centerY, 2));
        var slope = Math.atan2(curY - centerY, curX - centerX)*180/Math.PI;

        // Use unprefixed transform
        $("#line").css({
            "width": + width +"px",
            "height": "4px",
            "transform": "rotate(" + slope + "deg)"
        });
    }
});

See fixed fiddle here: http://jsfiddle.net/teddyrised/hepbob75/12/