Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Variable outside of function?

1| <script type="text/javascript">
2|    function more() {
3|          $("#innerSub2").animate({ scrollTop: "+=240px" },1000);
4|          var count = 1;
5|          document.getElementById("dot" +count).style.color="#c7c9e9";
6|          var count = count + 1;
7|          document.getElementById("dot" +count).style.color="#6464c1";
8|        }
9|     </script>

Helo, I am pretty new to javascript. So sorry if this is a stupid question.
On the first click event the variable works as i need it to( line 5, count=1)(line 7, count=2)
But on second click event i need ( line 5, count=2)(line 7, count=3) but as you can see it resets to 1 with line 4.
So the question is, how can I declare | var count = 1; | outside of function more() so it won't reset my variable? or if there is any other way to do this..
Also if there is a way to stop variable count from exceeding 3, please share
Thank you

like image 304
iamruskie Avatar asked Nov 04 '11 01:11

iamruskie


1 Answers

You can define a variable outside your function, so it wont be erased, this way the scope of your variable will be global, having a lot of global variables is considered not to be a good practice you can learn more about scope and javascript/jquery basics in this book http://jqfundamentals.com/book/index.html#example-2.44

<script type="text/javascript">
   var count = 1;
   function more() {
         $("#innerSub2").animate({ scrollTop: "+=240px" },1000);          
         document.getElementById("dot" +count).style.color="#c7c9e9";
         count = count + 1; //removed the var word.
         document.getElementById("dot" +count).style.color="#6464c1";
       }
</script>
like image 144
ElHacker Avatar answered Sep 28 '22 07:09

ElHacker