Search code examples
jqueryself

How to use 'self' in jQuery object?


I made simple color change function and organize it as object. but how to use self in the object?

this is object that I made and first and second is working well, while 3rd isn't working..

var Color = {
    textColor:function (color){
        $('body').css('color', color);
    },
    backgroundColor:function (color){
        $('body').css('backgroundColor', color);
    },
    inputColor:function (color){
        $(self).css('backgroundColor', color);
    }
}

If I use commented out query, it works well while Color.inputColor('color') not working. I want to organize it as object.

function highlightInput(self){
    $(document).ready(function(){
        // $(self).css('backgroundColor', 'lightyellow');
        Color.inputColor('lightyellow');
        $(self).blur(function(){
            // $(self).css('backgroundColor', 'white');
            Color.inputColor('white');
        });
    });
}

thank you in advance!


Solution

  • Easiest solution would be to just pass it as a parameter to inputColor (and to any other functions of Color that need a reference to self):

    var Color = {
        textColor:function (color){
            $('body').css('color', color);
        },
        backgroundColor:function (color){
            $('body').css('backgroundColor', color);
        },
        inputColor:function (color, self){
            $(self).css('backgroundColor', color);
        }
    }
    

    and

    function highlightInput(self){
        $(document).ready(function(){
            Color.inputColor('lightyellow', self);
            $(self).blur(function(){
                Color.inputColor('white', self);
            });
        });
    }