John
John

Reputation: 3916

Possible scope issue with jQuery plugin?

I'm trying to make a jquery plugin (just for fun) and I can't seem to a certain portion to do what I want.

(function($){

    var resetText = function(){ if (this.value == "") this.value = this.title; }
    var clearText = function(){ if (this.value == this.title) this.value = ""; }

    $.fn.placeHolder = function() {
        return this.each(function(){
            resetText(); // <-- this doesn't work
            $(this).focus(clearText).blur(resetText);
        });
    };
})(jQuery);

Basically, I want the title attribute to be copied over to the value attribute (if the value is empty) on doc.ready AND on field.blur

As it is now, it works onBlur but not on document.ready

I have a feeling it's a scope thing but honestly I don't know how to fix it.

See for yourself: http://jsfiddle.net/Usk8h/

Upvotes: 2

Views: 116

Answers (2)

user113716
user113716

Reputation: 322622

You have a this issue, not a scope issue.

Do this instead:

resetText.call( this );

The .call() method allows you to set the value of this in the resetText() function to whatever you pass as the first argument.

In this case you're passing the DOM element represented by this in the .each().


EDIT:

You could actually reduce your the plugin down to this:

$.fn.placeHolder = function() {
    return this.focus(clearText).blur(resetText).blur(); // <-- triggers blur
};

Upvotes: 3

James Montagne
James Montagne

Reputation: 78780

It does appear to be a scope issue. How about this?

http://jsfiddle.net/Usk8h/1/

(function($){

    var resetText = function(myThis){ if (myThis.value == "") myThis.value = myThis.title; }
    var clearText = function(myThis){ if (myThis.value == myThis.title) myThis.value = ""; }

    $.fn.placeHolder = function() {
        return this.each(function(){
            resetText(this);
            $(this)
                .focus(function(){
                    clearText(this);
                }).blur(function(){
                    resetText(this);   
                });
        });
    };
})(jQuery);

Upvotes: 0

Related Questions