Rutwick Gangurde
Rutwick Gangurde

Reputation: 4912

jQuery.css not working for element added with append?

I'm using a modular pattern for writing my JS code. I have an object with references to all my dom elements. I have put the selector for a div that I'm adding at a later point in my code execution. When I add that div, and use jQuery.css using the reference I stored in my references object, it doesn't work.

NameSpace = {
    objects: {
        someButton: $('.someButton'),
        someDiv: $('.someDiv'),
        myDiv: $('.myDiv'), //This will be added later
        //Other references
        .
        .
    },

    bindHandlers: {
        NameSpace.objects.someButton.on('click', someEventHandler);
        //Other bindings
        .
        .
    },

    eventHandlers: {
        someEventHandler: function(e){
            var div = jQuery('<div class="myDiv"></div>');
            NameSpace.objects.someDiv.append(div);

            //Doesn't work! If I use jQuery('.myDiv'), then it works,
            //but kills my modular style
            NameSpace.objects.myDiv.css({ //some styles });
        },
        //Other event handlers
    }
}
//Other code

This approach works fine for objects that exist in the page, but isn't working for a div that I add like above.

Any help?

Upvotes: 1

Views: 1760

Answers (1)

Florian F.
Florian F.

Reputation: 4700

Javascript is procedural, this line myDiv: $('.myDiv') is computed only once and not everytime you call it.

It means that your selector $('.myDiv') is filled at the start of your page.

To resolve this you'd have to make your variable a function

objects: {
        someButton: $('.someButton'),
        someDiv: $('.someDiv'),
        myDiv: function(){ return $('.myDiv'); }, //This will be added later
        //Other references
        .
        .
    },

It should recalculate the selector everytime you call it.

Let me know if the trick works.

Upvotes: 3

Related Questions