StackOverflow: Google Docs hyperlink functionality
This imitates the Google Docs hyperlink functionality.
http://stackoverflow.com/questions/5752147/jquery-get-textarea-cursor-caret-x-y-position-and-show-a-div-underneath/
HTML
<link rel="stylesheet" href="https://github.com/taitems/Aristo-jQuery-UI-Theme/raw/master/css/Aristo/jquery-ui-1.8.7.custom.css">
<div id='main' role='main'>
<h1>Hello, there.</h1>
<p>You look like you are trying to copy <a contenteditable="true" href='http://docs.google.com/'>Google docs</a> hyperlink functionality. Need some help with that?</p>
</div>
CSS
html {
height: 100%;
}
body {
margin: 0;
padding: 0;
height: 100%;
color:#444;
}
body { font:13px/1.231 sans-serif; *font-size:small; } /* Hack retained to preserve specificity */
select, input, textarea, button { font:99% sans-serif; }
#main {
position:relative;
padding:.33em;
}
#main h1 {
font-size:1.5em;
margin-bottom:.33em;
color:#000;
}
#main p {
text-indent:2em;
}
.linkContainer {
position:absolute;
margin:.33em 0 0;
padding:.33em;
font-size:.8em;
background:#dfebfd;
border:1px solid #bbd5fd;
color:#1e1f6e;
}
JavaScript
(function($) {
var $body = $('body');
$body.delegate('a', 'keyup', function(e) {
var $this, href, position, $div, $change, $remove;
$this = $(this);
href = $this.attr('href');
position = $this.position();
e.preventDefault();
$remove = $('<a>', {
'href': '#',
'text': 'Remove'
}).bind('click', function(e) {
$this.after($this.text()).remove();
$div.remove();
});
$change = $('<a>', {
'href': '#',
'text': 'Change'
}).append(' ').bind('click', function(e) {
$div.remove();
$("<form><fieldset><label for='editText'>Text to display: </label><input id='editText' value='" + $this.text() + "'/></fieldset><fieldset><label for='editHref'>Where you want it to go: </label><input id='editHref' value='" + href + "'/></fieldset></form>").dialog({
modal: true,
title: 'Edit link',
width: 400,
buttons: {
'Ok': function() {
$this.text($('#editText').val()).attr('href', $('#editHref').val());
$(this).dialog("close").dialog("destroy").remove();
},
'Cancel': function() {
$(this).dialog("close").dialog("destroy").remove();
}
}
});
});
$div = $('<div>', {
'class': 'linkContainer'
}).append("Go to link: <a href='" + href + "'>" + href + "</a> ").append($change).append($remove).css({
'top': position.top + $this.outerHeight(),
'left': position.left
}).appendTo($body);
$body.bind('click', function(e) {
if (!$(e.target).hasClass('linkContainer')) {
$(this).unbind(e);
$div.remove();
}
});
});
}(jQuery));