position input after closest span, if it exists, in jquery
I currently have this function which appends an "input" to the #cursor-start div:
var $cursorStart= $("#cursor-start");
$("#main-edit").click( function() {
var cursorExists = $("#cursor").length;
if (!cursorExists){
$cursorStart.append("<input type='text' id = 'cursor' />");
$("#cursor").markCursor();
}
if (cursorExists){
$("#cursor").focus();
}
What I want to do now is add the input after the closest span if it exitst. There are other functions called enterText and markCursor that are called when typing:
jQuery.fn.markCursor = function(e){
$(this).focus();
$(this).keyup(function(e) {
$cursorStart.enterText(e);
});
};
jQuery.fn.enterText = function(e){
var $cursor = $("#cursor");
if( $cursor.val() && e.keyCode != 32 ){
var character开发者_StackOverflow社区 = $("#cursor").val();
$cursor.val("");
character = character.split("").join("</span><span class='text'>");
$("<span class = 'text'>"+character+"</span>").insertBefore($cursor);
}
});
I want now to position the input depending on where the user clicks, would .offset() or .position() be of help here?
HTML :
<span>a</span>
<span>b</span>
<span>c</span>
<span>d</span>
clicking near a and b would result in an input after "a"
Instead of listening for clicks on #main-edit
, listen for the clicks on the span
s themselves:
$('#main-edit span').click(function() {
$(this).after('<input type="text" id="cursor" />');
});
Or use delegate
:
$('#main-edit').delegate('span', 'click', function() {
$(this).after('<input type="text" id="cursor" />');
});
And here's the fiddle: http://jsfiddle.net/YxfWX/
精彩评论