Note that there are some explanatory texts on larger screens.

plurals
  1. POJavaScript global variable reverts back to original value after change?
    primarykey
    data
    text
    <p>I have a global variable <code>window.current_index</code> that records the application state, i.e. which page we are on in a javascript web app. </p> <p>Then I have a block of code that goes to the next page, and increments <code>window.current_index</code> to reflect the state change (took out irrelevant DOM manipulation code that just would make it harder to see the issue):</p> <pre><code>$('#next-page').click(function() { console.log('current index is ' + window.current_index); var next_index = window.current_index + 1; console.log('next index is ' + next_index); //update the index window.current_index = window.current_index + 1; console.log('current index is now ' + window.current_index); }); </code></pre> <p>It works fine the first time, but when I click it again, I don't get the intended result. With the console logging, I get an odd output:</p> <pre><code>current index is 2 main.js:57 next index is 3 main.js:59 current index is now 3 main.js:62 current index is 2 main.js:57 next index is 3 main.js:59 current index is now 3 main.js:62 </code></pre> <p>It appears that <code>window.current_index</code> <strong>hasn't been updated when I fire the function again, even though it said it was before?</strong> Isn't this variable of appropriate scope so that I can store the app state in it and it will persist across the event handler calls? Obviously not since it isn't working... what have I done wrong? I'm guessing this is a scope issue but I can't figure out for the life of me how I would do it correctly... :/</p> <p><strong>Clarification:</strong> there is no page reload going on here, page does not reload in between actions. I just show a new "frame" via JavaScript hiding/showing. I'm also not using <code>iframes</code>, I'm literally just using <code>$('div').hide()</code> and <code>$('div').show()</code> on a one-pager site. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload