1

I am trying to change value if there is a mouse move on the page, but it always stays the same. It always writes "no" on click.

var desifre = "no";

$('body').bind('mousemove', function(e){
var desifre = "yes";
});

$('#test').click(function(){
document.write(desifre);
});

What is the correct way to change the value, if there is mouse move on the page ?

user198989
  • 4,574
  • 19
  • 66
  • 95
  • [Here](http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript/500459#500459) you can read about the scope of variables in JavaScript – Carlos Mayo Nov 20 '15 at 07:54

3 Answers3

5

I think the problem is you are redefining the variable within the function, have you tried the following. By redefining the variable you are changing the scope and assigning the value to a local variable not the global variable!

var desifre = "no";

$('body').bind('mousemove', function(e){
   desifre = "yes";
});

This article may be helpful: http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/

Also do you need to pass the event e into the function if you are not using it?

Mike Sav
  • 14,805
  • 31
  • 98
  • 143
4

You actually define a local variable instead of changing the outer/global one. Change it to look like this:

$('body').bind('mousemove', function(e){
   desifre = "yes";
});
Rob
  • 11,492
  • 14
  • 59
  • 94
1

try this following code,when mouse is move,index increment and desifre value is will be yes in each moving http://jsfiddle.net/a31jwxj5/1/

Yasemin çidem
  • 623
  • 8
  • 17