ciscoheat
ciscoheat

Reputation: 3947

Trigger extra mouse click event in same location as first

I have some html, and want to create an input field when clicking a paragraph. That is no problem, but then I'd also like the text cursor to move where the click occured. This can be done simply by clicking again of course, but I'd like this to happen in a single click.

It would be nice to use the first click event to trigger another right after the input field has been created, which would (hopefully) use the mouse coordinates of the first event to move the text cursor to the correct location. Is this possible?

I'm using jquery, so if that makes it easier, please use it for your answer. Thanks for your help!

Upvotes: 0

Views: 175

Answers (1)

towr
towr

Reputation: 4167

Here's an approximate solution. It work by calculating the approximate character offset from the number of characters in the text, the width of the text and the relative mouse-offset.

The function for setting the cursor position (once we calculated it) comes from https://stackoverflow.com/a/841121/1961666

http://jsfiddle.net/4LmZ9/

$.fn.selectRange = function(start, end) {
    if(!end) end = start; 
    return this.each(function() {
        if (this.setSelectionRange) {
            this.focus();
            this.setSelectionRange(start, end);
        } else if (this.createTextRange) {
            var range = this.createTextRange();
            range.collapse(true);
            range.moveEnd('character', end);
            range.moveStart('character', start);
            range.select();
        }
    });
};

$('span').on('click', function(evt)
{
    var left = $(this).offset().left;
    var width = $(this).width();
    var clen = $(this).text().length;
    var offset = parseInt((evt.pageX - left)/width * clen);
    $(this).replaceWith($('<input />').val($(this).html()));
    $('input').trigger('focus').selectRange(offset);
});

(You can get better precision if you calculate the width of each character and taking that into account, if it's important.)

Upvotes: 1

Related Questions