0

I am trying to write a script which I want to put in my html website. What this script does is that it changes text with change in mouse cursor position. For eg. if user is on (x,y)=(1,1) then some text will be displayed while if on (x,y)=(2,2) some other random text will be displayed.

var text = [ 'I am human.']

I am not sure about how to connect this to a mouse event. Like if pointer moves, display any random text from list of text. Can anyone provide the code? Will really help me. Thank You!

Dvorak
  • 169
  • 1
  • 2
  • 11

3 Answers3

2

Bind mousemove on window or something, then use the screenX / screenY / clientX / clientY / etc on the event object.

A simple demo:

var $message = $('#message');

$(window).on('mousemove', function(e) {
    if(e.clientX > e.clientY) {
        $message.text('top right triangle');
    } else {
        $message.text('bottom left triangle');
    }
});

HTML:

<div id="message">Move the mouse.</div>

http://jsfiddle.net/qjtnd/

Community
  • 1
  • 1
Dogbert
  • 212,659
  • 41
  • 396
  • 397
  • Although one of the tags was jquery, I don't think jquery is necessary in this case, it's easily accomplishable without it, but if he wants to use jquery it's his choice. +1 for good answer. – Zachrip May 19 '13 at 16:46
  • How can I bind the function with every pixel rather than (e.clientX > e.clientY), I want that random text from 'var Text' is displayed if the mouse is moved even a pixel? Thanks for the answer though :D – Dvorak May 19 '13 at 16:49
  • @Dvorak, just remove the `if else`, and put in `$message.text(text[~~(Math.random() * text.length)]);` – Dogbert May 19 '13 at 16:53
1

Since you're using JQuery, you can just use the mouse move function and if you want effects, you can use JQuery's animate.

Javascript:

$(document).mousemove(function(){
   var randText = text[Math.floor(Math.random()*text.length)];
   var div = $("#textDiv");
   div.stop().animate({"opacity": "0"}, 100, function(){
       $(this).html(randText);
       $(this).stop().animate({"opacity": "1.0"}, 100);
   });
});

HTML:

<div id="textDiv"></div>
nhydock
  • 2,246
  • 1
  • 15
  • 11
0
var text = [ 'I am human.'
            , 'Some text here.'
            , 'I love technology.'
            , 'You are a good person'
            ]
$(document).mousemove(function(event) {
   var randomItem = text[Math.floor(Math.random()*text.length)];
    alert(randomItem);
});

See at http://jsfiddle.net/2raaa/

Manish Jangir
  • 505
  • 3
  • 9
  • Seeing that he wants it to change on every pixel movement, using alert could be rather annoying/problematic. It would be better to either use Console.log or print out within some div. – nhydock May 19 '13 at 16:53
  • Ya sure.But he can do this simple task now. – Manish Jangir May 19 '13 at 16:55