How to Store a Global Value (Not Necessarily a Global Variable) in Jquery

How to store a global value (not necessarily a global variable) in jQuery?

You can create a namespace inside the jQuery object, like so:

$.mynamespace = { 
myVar : "something",
myVar2 : "somethingElse"
};

or:

$.mynamespace = {};
$.mynamespace.myVar = "something";
$.mynamespace.myVar2 = "somethingElse";

Bear in mind, any plugin method named 'mynamespace' will be overwritten so be sure to use a sensible name.

How to cleanly deal with global variables?

It is best practice to not clutter the global scope. Especially since other frameworks or drop-in scripts can pollute or overwrite your vars.

Create a namespace for yourself

https://www.geeksforgeeks.org/javascript-namespace/

More here: https://stackoverflow.com/search?q=namespace+javascript+global

Some examples using different methods of setting the vars

myOwnNS = {}; // or window.myOwnNS
myOwnNS.counter = 0;
myOwnNS["page1"] = { "specificForPage1":"This is page 1"}
myOwnNS.page2 = { "specificForPage2":"This is page 2", "pagenumber":2}
myOwnNS.whatPageAmIOn = function { return location.href.substring(location.href.lastIndexOf('page')+4)}

How to create a global variable in jQuery

jQuery library is build from JavaScript. Here is how to create global variable in JavaScript.

var data = ["wake up","eat breakfast","code"];

alert(data[0]); // will display "wake up"

Use jQuery the local variable to global variable

remove the var in userLogin() function in order to use the globaly declared username variable

Is it ok to place all JS / jQuery variables at top of file? Global variables?

If this is a concern at all then you can just wrap your scripts in

(function(){
var ab = $('#div32');
var bc = 1000;
})()

and then they will be declared in function scope instead of global scope.

By writing ab = $('#div32'); you will be setting the first ab that javascript encounters to $('#div32'); This could be declared already or you'll be creating it when you try to set it. This isn't a security problem as much as it is a stability problem.

In terms of commas vs semicolons, you're not going to see a difference except for perhaps a slight decrease in the amount of data going down the wire.

var foo = 1, bar = 2;

is functionally the same as

var foo = 1;
var bar = 2;

Edit: As Joe pointed out, there is a third case I should have mentioned.

var foo = 1; bar = 2;

This will set variable foo inside function scope, and also create/modify variable bar in global scope (depending on whether or not bar already exists)

jQuery global variable, not working

Check, whether you have jquery or not. I have created a jsfiddle (https://jsfiddle.net/2kudvsr0/) for your code and its printing None (desired output).

Just make sure you are executing your code once jQuery is imported successfully.



Related Topics



Leave a reply



Submit