2

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/

Idan
  • 5,405
  • 7
  • 35
  • 52
Dennis
  • 75
  • 9

2 Answers2

0

you have to change the duration property of the jquery animate.

here is a working plunker :

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"
  }, 50, function() {
    $(this).text(randomItem);
    $(this).stop().animate({
      "opacity": "1"
    }, 1);
  });

});

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

HellYeah
  • 23
  • 5
  • Thanks for your quick answer HellYeah. I also tried this, but the result wasn't good, it doenst feels like its based on the mouse movement, because sometimes it is still changing when you stopped moving. – Dennis Aug 10 '17 at 09:44
0

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>
Idan
  • 5,405
  • 7
  • 35
  • 52