Scarface
Scarface

Reputation: 3913

how to make a function live

I have a enter function which makes it so my form will submit on enter. The only problem is my form does not exist until i click a button that appends it to the body. Is there a way to make my $.Enter function live? Thanks in advance for any suggestions.

//submit function
function submit_chatbox(){
alert('yo');
}

$.Enter('#message',submit_chatbox);

jQuery.Enter = function(element,callback) {
    jQuery(element).bind('keypress', function(event) {
        var code=event.charCode || event.keyCode;
        if(code && code == 13) {// if enter is pressed
            callback(event.target);
            event.preventDefault(); //prevent browser from following the actual href
        };
    });
};

Upvotes: 2

Views: 541

Answers (2)

Champo
Champo

Reputation: 3419

Just using live instead of bind will do it, asumming you're using a jQuery version that supports it.

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630389

To make it use .live(), it would look like this:

jQuery.Enter = function(element,callback) {
    jQuery(element).live('keypress', function(event) {
        var code=event.charCode || event.keyCode;
        if(code && code == 13) {// if enter is pressed
            callback(event.target);
            event.preventDefault(); //prevent browser from following the actual href
        };
    });
};

But... what you have lends it self well to a plugin, like this:

jQuery.fn.Enter = function(callback) {
    return this.live('keypress', function(event) {
        if(event.which == 13) {
            callback.call(this, event);
            event.preventDefault();
        };
    });
};

Then you'd call it like this:

$('#message').Enter(submit_chatbox);

Upvotes: 5

Related Questions