views:

167

answers:

2

jQuery Version: 1.4.1

I am attempting to write a simple watermark type plugin and I want to take advantage of live events since not all of the elements I need to use it on will exist during the page load, or they may be added and removed from the DOM. However, for some reason the events never fire.

Here is the not working code:

; (function($) {

    $.fn.watermark = function(text) {

        return $(this).each(function() {
            $(this).live('focusout', function() {
                if (this.value == "") {
                    this.value = text;
                }

                return false;
            });

            $(this).live('focusin', function() {
                if (this.value == text) {
                    this.value = "";
                }

                return false;
            });
        });
    }

})(jQuery);

I can get this to work without using live events. This code does work:

; (function($) {

    $.fn.watermark = function(text) {

        return $(this).each(function() {
            $(this).focusout(function() {
                if (this.value == "") {
                    this.value = text;
                }

                return false;
            });

            $(this).focusin(function() {
                if (this.value == text) {
                    this.value = "";
                }

                return false;
            });
        });
    }

})(jQuery);
+1  A: 

.live() needs a selector not a DOM element, in the place you're calling it, it's only on a DOM element, so instead of this:

$(this).each(function() {
        $(this).live('focusout', function() {

Try this (this is already a jQuery object):

this.live('focusout', function() {

It needs this because of how .live() works, when an event bubbles up to document it checks that selector...if there's no selector, there's no way for it to check. Also, if you have a DOM element and the event handler is for only it, .live() wouldn't make much sense anyway :)

Nick Craver
`$(this).each` should be replaced by `this.each` for the same reasons.
jAndy
@jAndy - Actually he doesn't need the `.each()` at all, just chained selectors :)
Nick Craver
Something doesn't seem right here. I thought you should always use return this.each? See: http://stackoverflow.com/questions/2678185/why-return-this-eachfunction-in-jquery-plugins
Corey Sunwold
Never mind Nick, I see whats going on now. Thanks.
Corey Sunwold
A: 

Take a look here.

http://stackoverflow.com/questions/1199293/simulating-focus-and-blur-in-jquery-live-method

RobertPitt
This shouldn't be necessary since I am using version 1.4.1. That question is a workaround since previous versions of jquery didn't supporting using focusin and focusout as live events.
Corey Sunwold