1

How do I access isExpanded, collapsedHeight and expandedHeight inside the jQuery click handler for element.
The way it's written now won't work because this means something else inside the click handler than it does outside of it.

function CoolSelect(element)
{
    this.element=element;
    this.isExpanded=false;
    this.collapsedHeight=$(element).height();
    this.expandedHeight=this.collapsedHeight+$('ul',element).height();

    $(this.element).click(function()
    {
        var newHeight;
        if(this.isExpanded){newHeight=this.collapsedHeight;}
        else{newHeight=this.expandedHeight;}
        $(this.element).animate({height:newHeight},100,'liniar');
    });
}

Thank you.

2 Answers 2

3

Copy the value of this to another variable in the outer function.

var that = this;

Then use that in the inner function.

Sign up to request clarification or add additional context in comments.

1 Comment

Out of curiosity, wouldn't it be easier if I just declared each class property as a var and just access it in the inside functions?
3

You need to save a reference to this. This code uses var that = this;

function CoolSelect(element)
{
    this.element=element;
    this.isExpanded=false;
    this.collapsedHeight=$(element).height();
    this.expandedHeight=this.collapsedHeight+$('ul',element).height();
    var that = this;

    $(this.element).click(function()
    {
        var newHeight;
        if(that.isExpanded){newHeight=that.collapsedHeight;}
        else{newHeight=that.expandedHeight;}
        $(that.element).animate({height:newHeight},100,'liniar');
    });
}

3 Comments

Thank you, Lime. I chose the answer that was posted first. Otherwise, yours was just as good.
16 seconds make all the difference :D
I had no other criteria. Haha.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.