Search code examples
jquerypositionmousemoveonmousemove

Change text on cursor position


I am trying to change a text based on the cursor position. It is working but the change sensitivity is way to fast. So I was wondering if there is a way to adjust this, that the change isn't that fast.

var text = ['Orange', 'Banana', 'Strawberry', 'Melon']
$(document).mousemove(function(event) {
  var randomItem = text[Math.floor(Math.random() * text.length)];
  var div = $("#message");

  div.stop().animate({
    "opacity": "1"
  }, 1, function() {
    $(this).text(randomItem);
    $(this).stop().animate({
      "opacity": "1"
    }, 1);
  });
});
#message { font-size: 54px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="message">Move the mouse.</div>

http://jsfiddle.net/2raaa/23/


Solution

  • I am sure you can formulate a better solution. In your case, you only focus on mouse movement, since you want to increase the sensitivity you can observe actual position of the mouse:

    var text = ['Orange', 'Banana', 'Strawberry', 'Melon']
    var pos = {x: 0, y:0};
    $(document).mousemove(function(event) {
      var randomItem = text[Math.floor(Math.random() * text.length)];
      var div = $("#message");
      if (event.pageX > pos.x+30 || event.pageY > pos.y+30 || event.pageY < pos.y -30 || event.pageX < pos.x-30) {
        pos.x = event.pageX;
        pos.y = event.pageY;
        div.stop().animate({
          "opacity": "1"
        }, 1, function() {
          $(this).text(randomItem);
          $(this).stop().animate({
            "opacity": "1"
          }, 1);
        });
      }
    });
    #message { font-size: 54px; }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="message">Move the mouse.</div>