LargeTuna
LargeTuna

Reputation: 2824

How to store variables for other jQuery scripts to use on the page.

I am trying to find the best methodology and have the cleanest code as possible on a project that I am working on.

I am using php and jQuery and displaying information on the page via ajax. When something changes on the page, some of the variables that are passed back into the page change. I need to store these values for other scripts on the page to use. What is the best approach for this.

Currently I am just storing these variables in hidden input fields with id's and then using jQuery to access them when needed. Is this a good approach or is there a better methodology? I don't want to have junky code that other developers look at and use and their punch line to their jokes.

Thanks!

Upvotes: 1

Views: 135

Answers (2)

Digital fortress
Digital fortress

Reputation: 737

You can make use of HTML5 sessionStorage object

an example of how you set it

sessionStorage.setItem("myKey", "myValue");

please check documentation below

Here

Upvotes: 0

Machavity
Machavity

Reputation: 31614

I find storing the variables inside your script is faster, especially since you're using them with existing JS. I would go further than some of the comments, however. If you're working with a series of fields and methods, it's best to build a JS object and keep everything together. This has the added benefit of being viewable inside your DOM inspector (Firebug, etc).

function MyClass(obj) {
     this.myvar = obj.val
}

MyClass.prototype.myFunc() {
    console.log(this.myvar);
}

newobj = new MyClass({"val":1});
newobj.myFunc();

Upvotes: 1

Related Questions