2

I try to create a variable on click, and to use it on another onclick action. But it seems that the variable doesn't exist when the second onclick try to use it.

$( "#search" ).click(function() {
    var myVariable = $(document).scrollTop();
});

$( "#gachette" ).click(function() {
    $('html, body').animate({scrollTop:myVariable}, 10);
});

Do you have an idea why it doesn't work?

KyleMit
  • 30,350
  • 66
  • 462
  • 664
Damien
  • 333
  • 1
  • 3
  • 17

3 Answers3

3

make your variable global.

$( "#search" ).click(function() {
   myVariable = $(document).scrollTop(); //global variable remove var from starting
});

var makes your variable local to the scope.

or declare you variable outside

var myVariable;
$( "#search" ).click(function() {
   myVariable = $(document).scrollTop();
});

Read What is the scope of variables in JavaScript? and Variable Scope (JavaScript)

Community
  • 1
  • 1
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
1

It's all about scope

var myVariable; // DEFINE OUTSIDE!

$( "#search" ).click(function() {
    myVariable = $(document).scrollTop(); // DON'T USE var HERE
});

$( "#gachette" ).click(function() {
    $('html, body').animate({scrollTop:myVariable}, 10);
});
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
0

And without globals :

$("#search").on('click', function() {
    $("#gachette").data('scrollTop', $(window).scrollTop());
});

$("#gachette").on('click', function() {
    $('html, body').animate({scrollTop: $(this).data('scrollTop')}, 10);
});
adeneo
  • 312,895
  • 29
  • 395
  • 388