CodeIgniter Forums
jQuery: execute function upon keydown - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: jQuery: execute function upon keydown (/showthread.php?tid=5330)



jQuery: execute function upon keydown - El Forum - 01-17-2008

[eluser]codex[/eluser]
I'm trying to execute a function upon keydown but I can't get it to work. saveChangesTitle() is a self defined function, but when I try to do it as below I get an error saying saveChangesTitle() is not a function. How do you do this the proper way?

Code:
jQuery('.eip-text').keydown(function(e){
                        if (e.keyCode == 13) {
                            e.saveChangesTitle(this, revert, i, title_id);
                            return false;
                        }
                    });



jQuery: execute function upon keydown - El Forum - 01-17-2008

[eluser]Nick Husher[/eluser]
I'm not familiar with jQuery, but is the type of argument e to your anonymous function a Javascript event? If that's the case, then saveChangesTitle isn't a function defined by Event, and you should probably find a less messy way of including it in your event handler. Here's how I'd do it:

Code:
(function() {
    var saveChangesTitle = function(element, revert, i, title_id) {
        ...
    };
    
    jQuery('.eip-text').keydown(
        function(e) {
            if (e.keyCode == 13) {
                saveChangesTitle(this, revert, i, title_id);
            }
        });
})();

Note, if you really want to define saveChangesTitle on your event object, you'd do it by executing the following code:

Code:
Event.prototype.saveChangesTitle = function(el, revert, i, title_id);



jQuery: execute function upon keydown - El Forum - 01-17-2008

[eluser]codex[/eluser]
Cool, that will work. Thanks!