Settings CSSvalues per mouse.x

It is this simple. I overrode the default mousemove event, and I replaced it with this:

function onDocumentMouseMove(e) {
  e.preventDefault();
  e.stopPropagation();
  mouse.x = (e.clientX / WIDTH) * 2 - 1;
  mouse.y = -(e.clientY / HEIGHT) * 2 + 1;

  var x = mouse.x + "px";
  $('#gun').css('left', x);
}

However, this doesn't work, the gun is just rendered as originally positioned. Please help, because I need to know basic stuff like this to be a programmer. I'm just too stupid. Maybe I need Stackoverflow just as compensation?

Thanks to all of you guys who work so hard to answer questions!

  • Noah

Answers 1

  • I think your code generally would work if you declare your WIDTH, HEIGHT, mouse right. I made a demo for you so you can see the result.

    $(document).ready(function () {
      /*
       * place jquery objects & constants declarations outside of 
       * event handler so you don't redeclare them every time the 
       * event fires.
       */
      var $gun = $('#gun');
      var WIDTH = $gun.css('width').match(/\d*/)[0];
      var HEIGHT = $gun.css('height').match(/\d*/)[0];
    
      $('.playground').on('mousemove', function (e) {
        e.preventDefault();
        e.stopPropagation();
    
        var mouse = {};
    
        // your definition of mousemove behavior
        mouse.x = (e.clientX / WIDTH) * 2 - 1;
        mouse.y = -(e.clientY / HEIGHT) * 2 + 1;
    
        // your DOM manipulations
        $gun.css('left', mouse.x);
      });
    });
    

Related Articles