JSFiddle - React, Tailwind, and code Playground

by Kevin Faulhaber

HTML

<img id="celine" src="http://omiyage.hd.free.fr/CVceline/wp-content/uploads/2014/04/cropped-copy-cropped-cropped-photo-profil-21.png">
<button id="stop">STOP THIS BASTARD</button>

CSS

img {
    position: absolute;
    top: 100px;
    left: 100px;
    width: 30px;
    height: auto;
}

JavaScript

//The amount the image will move
var HOP = 1;
var TIME = 5; //milliseconds it will take before the image moves again
//initiating standard mouse coords
var mouse = {
    x: 0,
    y: 0
};
//adding a listener on the document for mousemove to update mouse position
document.addEventListener('mousemove', function (e) {
    mouse.x = e.clientX || e.pageX;
    mouse.y = e.clientY || e.pageY
}, false);

//getting the image
var $img = document.getElementById('celine');
var si_id = setInterval(function () {
    //every 50 miliseconds we do this

    //getting img position (sylte.left/top will not return the position)
    var tempL = $img.offsetLeft;
    var tempT = $img.offsetTop;

    //testing to see where the mouse is relative to the image
    if (mouse.x > tempL) {
        console.log('true: ' + mouse.x + ' : ' + tempL);
        $img.style.left = tempL + HOP + 'px';
    } else {
        console.log('false: ' + mouse.x + ' : ' + tempL);
        $img.style.left = tempL - HOP + 'px';
    }
    if (mouse.y > $img.offsetTop) {
        console.log('in');
        $img.style.top = tempT + HOP + 'px';
    } else {
        console.log('in');
        $img.style.top = tempT - HOP + 'px';
    }
}, TIME);

var button = document.getElementById('stop');
button.onclick = function(){
    clearInterval(si_id);
};