1

I am trying set selectors as global variables or namespaces.. I am not really sure if this is the correct terminology or if I am approaching this properly.

I would like to be able to do something like the following...

$.namespaceA = $('#myFirstDiv');
$.namespaceB = $('#mySecondDiv');


function myFirstFunction(){
   $.namespaceA.hide();
   $.namespaceB.css();
}

function mySecondFunction(){
   $.namespaceB.show();
}

This is a very basic example of how I want to use them. Basically the end goal is to set a group of global selectors which can be easily used through multiple functions. I don't know if this is right or if this is ideal which is why I am asking. Thanks in advance.

khollenbeck
  • 16,028
  • 18
  • 66
  • 101
  • you can refer to :http://stackoverflow.com/questions/527089/is-it-possible-to-create-a-namespace-in-jquery – Ankur Aug 29 '12 at 17:47
  • I have seen this but don't really understand it. Also maybe namespace isn't best. Maybe what I really need is variables.. – khollenbeck Aug 29 '12 at 17:50

3 Answers3

1

Why don't you simply make the global var's? (They can hold jQuery wrapped sets without a problem)

// When creating variables holding wrapped sets it is common naming to have 
// a $ following it (I find this rather annoying, since you can't easily double click
// on the var, in order to copy/paste it etc, so I always use _ underscore (personal preference)

var _div1 = $('#myFirstDiv'); // you will see a lot of people do div1$
var _div2 = $('#mySecondDiv'); // or div2$ (signifying the jQuery wrapped set)

_div2.hide();

//These could be used within multiple functions etc... No need for namespaces here!

function Whatever () {
    console.log(_div1);
    _div1.css('background', '#000');
}

$('#linkTrigger').on('click', function () {
    Whatever(); 
    _div2.fadeIn();
});

jsFiddle DEMO

$.nameSpaceHere is more for if you are trying to -extend- jQuery and add your own utility functions of some sort.

Mark Pieszak - Trilon.io
  • 61,391
  • 14
  • 82
  • 96
1

Similar to mcpDESIGNS:

http://jsfiddle.net/nqrvf/

<div id="myFirstDiv">first</div>
<div id="mySecondDiv">second</div>

var namespaceA = $('#myFirstDiv');
var namespaceB = $('#mySecondDiv');

$("#myFirstDiv").click(function() {
  namespaceA.hide();
});

$("#mySecondDiv").click(function() {
  namespaceA.show();
});
Lowkase
  • 5,631
  • 2
  • 30
  • 48
1

You can declare global variable without "var" keyword.

div = $('#myFirstDiv');

we can declare variable it inside any function it act as global variable.

YogeshWaran
  • 2,291
  • 4
  • 24
  • 32