Search code examples
javascriptjquerymouseeventfade

Image follow mouse pointer and fades


I am trying to create a image that follows the cursor and 'prints'/draws itself and fades each individual image that has been 'printed'/drawn after x amount of seconds.

So far I have managed to get the image to follow the cursor, just unsure of how to create a function or a way that would make each individual image fade away after a certain amount of time?

I have created a JS Fiddle to help with my explanation.

JS

(function() {
"use strict";

document.onmousemove = handleMouseMove;
function handleMouseMove(event) {
  var imgFollow, eventDoc, doc, body, pageX, pageY;

  event = event || window.event; // IE-ism

  // If pageX/Y aren't available and clientX/Y
  // are, calculate pageX/Y - logic taken from jQuery
  // Calculate pageX/Y if missing and clientX/Y available
  if (event.pageX == null && event.clientX != null) {
    eventDoc = (event.target && event.target.ownerDocument) || document;
    doc = eventDoc.documentElement;
    body = eventDoc.body;

    event.pageX = event.clientX +
      (doc && doc.scrollLeft || body && body.scrollLeft || 0) -
      (doc && doc.clientLeft || body && body.clientLeft || 0);
    event.pageY = event.clientY +
      (doc && doc.scrollTop  || body && body.scrollTop  || 0) -
      (doc && doc.clientTop  || body && body.clientTop  || 0 );
  } 

  // Add an image to follow the cursor     
  imgFollow = document.createElement('div');
  imgFollow.className = "imgFollow";
  imgFollow.style.left = event.pageX + "px";
  imgFollow.style.top = event.pageY + "px";
  document.body.appendChild(imgFollow);

  }
})();

CSS

.wrapper {
  height: 100vh;
  width:100%;
  background-color:green;
  overflow:hidden;
  position:relative;
}
.imgFollow {
  width: 32px;
  height: 32px;
  position: absolute;
  opacity:0.3;
  background-repeat:none;
  background-image:url('http://static.wfu.edu/images/icon-help-32x32.png');
  transform: translate(-50%, -50%);
}

Solution

  • Add them.

    JS

    setTimeout(function () {
        imgFollow.className = "imgFollow fade-out"
    },1000);
    

    CSS

    .fade-out{
        transition: opacity 1s;
        opacity: 0 !important;
    }