Tom Starkie Tom Starkie - 5 months ago 17
CSS Question

Keep image centered after updating x with mouse position

I have a script that moves an image slightly to the left or right when the user moves their mouse. The problem is this image is always in the top left of my window when I need it to always stay in the center.

<html>
<head>

</head>
<body>

<img id="logo" src="logoHeader.png" style="position:absolute;" />
</body>

<script lang="javascript">

function updateLogoPosition( e )
{
var logo = document.getElementById("logo");
var m = e.x / 12;
logo.style.left = m + "px";
}

document.onmousemove = updateLogoPosition;

</script>
</html>

Answer

You would have to do some more calculation to do this.

You need to know the width and height of the viewport to find the middle. Then you need to normalise the mouse position so that you calculate the offset from the centre line not from the top left as you e.x was doing.

Something like this should do it, where "modifier" will allow you to change the violence of the offset.

<html>
<head>
</head>
<body>

<img id="logo" src="http://placehold.it/150x150" style="position:absolute;" />

<script>

    document.onmousemove = updateLogoPosition;

    function updateLogoPosition( e ){

        // Get height and width of body
        var bodyHeight = document.body.clientHeight; 
        var bodyWidth = document.body.clientWidth;

        // Get height and width of logo
        var logo = document.getElementById("logo");
        var logoWidth = logo.width;
        var logoHeight = logo.height;

        /* Normalise the mouse so that 0 is the centre 
        with negative values to the left and positive to the right */
        var x = (e.x / bodyWidth * 100) - 50;
        var y = (e.y / bodyHeight * 100) - 50;

        // Calculate the position of the logo without mouse manipulation
        var leftOffset = (bodyWidth/2 - logoWidth/2); 
        var topOffset = (bodyHeight/2 - logoHeight/2);

        // Set violence of offset 
        var modifier = 0.5;

        // Add the mouse offset to the central position
        leftOffset += (x * modifier); 
        topOffset += (y * modifier);


        // Apply the calculated position to the logo
        logo.style.left = leftOffset + "px";
        logo.style.top = topOffset + "px";
    }

</script>

</body>
</html>