dotnetnoob
dotnetnoob

Reputation: 11350

Declare global jquery objects

Below is some typical jquery that I'm working with. As you will see, variables are declared at a global scope (excuse the terminology), however, I wondered if it was also possible to declare a jquery objects the same way that cn, declares class names.

For instance: var jq = { $html : $('html')};

I haven't managed to get any type of syntax to work as yet.

Thanks in advance.

var Nav = function () {

    var pub = {},
    cn = {
        open: "mobile-nav-open"
    };

    function toggleNav(e) {

        e.preventDefault();

        $html = $('html');

        if ($html.hasClass(cn.open)) {
            $html.removeClass(cn.open);
        } else {
            $html.addClass(cn.open);
        }
    };

    function setupBindings() {
        $(document).on("click", "#navicon", toggleNav);
    };

    pub.init = function () {
        setupBindings();
    };

    return pub;
} ();

Upvotes: 0

Views: 54

Answers (2)

Yeasin Abedin
Yeasin Abedin

Reputation: 2453

Javascript object uses name-value pairs. if you declare any anonymous variable inside an object, that context of that variable would be the object

var hellow = 'hh'
var x = {
    hellow: 'abc'
}

console.log(hellow)
console.log(x.hellow)

Upvotes: 0

Quentin
Quentin

Reputation: 944020

jQuery objects are just a class of JavaScript object. There's nothing special about them.

The syntax is the same as your existing code.

Use a : where you have a = inside your object literal.

Upvotes: 2

Related Questions