ksrb ksrb - 2 years ago 220
Javascript Question

Jquery variable not instantiated until click event

Problem: Element is not 'maxing' until user double clicks on the red square.

Basically the variable 'clicked' is being instantiated onClick instead of being instantiated before hand. The resulting behavior is that the user has to click once for the 'clicked' variable to be instantiated and then the function works as desired.

Here is the JSFiddle

And the important sections of code:

var container = $(this).parents('.container');
var paragraph = $(container).find('.text');
if (this.clicked == 0) {
container.removeClass("large-4");
container.addClass("large-8");
paragraph.removeClass("hide");
this.clicked = 1;
}


Any help is appreciated thanks!

Details (Don't have to read :D):

The reason I'm doing this inverted selection (selecting a child element and then the parent element) is because there will be many of these '.container' elements and each one needs to have the same respective min/max functionality by clicking on a minmax icon.

Obviously the method is not referencing the single local 'clicked' class variable. That doesn't even make sense as each element requires its own 'clicked' variable.

If there is a better way of doing this I'm open to anything, but even so it would be nice to figure this specific problem out as it would help my overall understanding of Jquery.

I'm using Foundation's framework on this project for those familiar with the class names.

I have this odd feeling that this has something to do with closure, but yea...don't know nearly enough about JS or JQuery to really figure this one out.

cfs cfs
Answer Source

In a jQuery event handler this refers to the object that triggered the event. So in your click callback, this no longer refers to your instance of Artist. To get around this, you can create a variable that and set it to the Artist instance. Thanks to javascript closures, you can refer to that and still have access to the instance.

Working Demo

Artist.clickHandler = function () {
    var that = this;
    //this.clicked is undefined until the event is actually fired
    that.clicked = 0;
    $('.minmax').click(function () {
        if (typeof that.clicked === 'undefined') {
            console.log("that.clicked is undefined");
        } else {
            console.log("that.clicked is defined");
        }
        //rest of handler here
    });
};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download