I have this code right now:
$(document).ready(function () {
$("div#main-edit").click( function() {
var cursorExists = $("input#cursor").length;
if (cursorExists == false){
$("div#cursor-start").append("<input type='text' id = 'cursor' />");
$("input#cursor").focus();
}
});
$("input#cursor").keydown(function() {
$("div#cursor-start").enterText();
});
jQuery.fn.enterText = function(){
alert("hello");
};
});
The function enterText is not called in this situation though. It seems like the fix should be easy for this. Is it because jquery finds nothing to select (input#cursor) when the document loads up?
I think this code has problems because you are calling this;
before the object
input#cursorhas been created by your code. Thus, it won’t find the object and can’t install an event handler for it. I would suggest you change your code to this which installs the event handler only after the object is created:The alternative would be to use
.live("keydown", function() {})instead of.keydown()which allows you to install some event handlers before the object exists (you can read the jQuery doc on it to understand further).FYI, you get a lot worse performance in jQuery when you use selectors like “input#cursor” instead of just “#cursor”. The latter gets optimized to use document.getElementById(). The former does not and takes a much longer code path. Since there is only one object in the page with any given ID, there should be no reason to quality it with the tag type. Just use “#main-edit”, not “div#main-edit”.