html5 javascript, global variables -


how create variable defined when page loaded , not in script?

<script>       var comp = 0;      function mmove(e)      {                  var x = e.screenx;                     if (x > comp + 80)          {              comp = x;              somethingcool();          }             }          </script>
    <video id="vid_id" onclick="vidclick()" onmousemove="mmove(event)" controls tabindex="0" autobuffer preload>          <source type="video/mp4; codecs=&quot;avc1.42e01e, mp4a.40.2&quot;" src="test.mp4"></source>          <p>sorry, browser not support &lt;video&gt; element.</p>      </video>

i have video , onmousemove event. want run somethingcool() function every time mouse moves along x-axis 80 pixels. need way store comp variable.

after mentioned reloading page has sript. problem obvious. your overwriting values. here possible solutions

solutions

1. make sure move variable declaration out of page. move main page. or else everytime page loaded value set 0.

2. use localstorage store values. can this.

<script>      if(localstorage.getitem("compvalue")){  //first time page load storage undefined set value 0. on consecutive calls if block not execute , hence value not overwritten.      localstorage.setitem("compvalue", 0);    }      var comp = localstorage.getitem("compvalue"); //read storage     function mmove(e)     {                 var x = e.screenx;                    if (x > comp + 80)         {             comp = x;             somethingcool();         }            }         </script> 

i woud prefer option 1, task not complicated use storages. make variable global , take care not overwrite it


Comments