user2971850
user2971850

Reputation: 31

How to have a constant value for a variable across many html pages using javascript?

I have a website with two web pages. In page1 when a button gets clicked it loads page2 and in page2 when a button gets clicked it loads page1.

The problem is i have a variable var c=0 in .js file that increases by 1 when page two loads and doesn't stay 1 when page1 loads rather it becomes 0 again.

Is there a way by which when var c increases to 1 it stays 1 over all pages till i change it again ?

Upvotes: 1

Views: 2117

Answers (3)

Nevin
Nevin

Reputation: 3306

These are the few options available:

  • Cookies: Click here

  • Local Storage : here or here

  • JSON data: here

  • Or add them into your database/webserver.

It all comes down to you and your project.. Good luck with your project!

Upvotes: 0

Deepu--Java
Deepu--Java

Reputation: 3840

Pass the value in url's query string and fetch in other page increase it and set to query string again for next request.

page2.jsp?c=0

Upvotes: 1

SomeKittens
SomeKittens

Reputation: 39522

In short: You can't store it as a regular variable if the page is reloading.

You might be able to get away with a single-page app framework like AngularJS, but that's really not worth re-archetecting your codebase for.

Instead, try putting your data in localStorage. You can only store strings there, but most things that aren't functions store well with JSON.stringify.

For example:

page1.js

var myVar = 'hello';
localStorage.setItem('myVar',myVar);

page2.js

var myVar = localStorage.getItem('myVar');
console.log(myVar); // Logs 'hello'

Upvotes: 0

Related Questions