Mouse Box

Written by @kerixa 21 August 2012

In this code, a box with a text inside follows the cursor. If the cursor stays in one place, this box also stays in the same place, and by moving the mouse cursor, this box follows it. You can use this code when you want your site name, or any other text, to be in front of the user's eyes or when you want to give a new message or alert to the user.

Code Snippet:

                                                
                                                <!-- this script is provided by https://www.javascriptfreecode.com coded by: Kerixa Inc. -->

<style>
body {
    margin: 0;
    background: #0094ff;
    height: 3000px;
}

#oscar {
    width: 170px;
    border: 5px solid #000;
}
</style>
<div id="wrapper">
    <svg xmlns="#" id="oscar" viewBox="-15 -20 281.837 51.837">      
        <text x="5" y="15" fill="#140862"  font-size="28px">Javascript Free Code!</text>
    </svg>
</div>

<script src='https://cdnjs.cloudflare.com/ajax/libs/gsap/2.0.2/TweenMax.min.js'></script>
<script>
console.clear();
var oscar = document.getElementById("wrapper");
document.addEventListener("mousemove", getMouse);
oscar.style.position = "absolute";
var oscarpos = { x: 0, y: 0 };

setInterval(followMouse, 50);

var mouse = { x: 0, y: 0 };
var dir = "right";

function getMouse(e) {
    mouse.x = e.pageX;
    mouse.y = e.pageY;

    if (mouse.x > oscarpos.x) {
        dir = "right";
    } else {
        dir = "left";
    }
}

function followMouse() {
    var distX = mouse.x - oscarpos.x - 15;
    var distY = mouse.y - oscarpos.y - 10;
    //Easing motion
    //Progressive reduction of distance 
    oscarpos.x += distX / 5;
    oscarpos.y += distY / 2;
    oscar.style.left = oscarpos.x + "px";
    oscar.style.top = oscarpos.y + "px";
    //Apply css class 
    if (dir == "right") {
        oscar.setAttribute("class", "right");
    } else {
        oscar.setAttribute("class", "left");
    }

}

TweenMax.set('#wrapper', { perspective: 800, force3D: true, transformStyle: "preserve-3d" });
</script><a target='_blank' href='https://www.javascriptfreecode.com' style='font-size: 8pt; text-decoration: none'>JavaScript Best Codes</a>                                                
                                            

Example:


About @kerixa

I am Krishna Eydat. I studied Software Engineering at University of Waterloo in Canada. I lead a few tech companies. I am passionate about the way we are connected. I would like to be part of something big or be the big deal!

K

Comments


Here you can leave us commments. Let us know what you think about this code tutorial!

0 / 300

TRENDING POST
1
2
3
4
5
VISITORS
Online Users: 12
Recent Members: admin_js, bloxio, yqaice, flooketsu, phuang_test
advertisement 2