Skip to content

Instantly share code, notes, and snippets.

@s-hiroshi
Created October 1, 2012 02:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s-hiroshi/3809170 to your computer and use it in GitHub Desktop.
Save s-hiroshi/3809170 to your computer and use it in GitHub Desktop.
JavaScript > editor
jQuery(function($) {
// 選択範囲取得は下記ライブラリを利用している。
// jQuery.selection
// http://madapaja.github.com/jquery.selection/
// テキストエリア(#input)の文字列を取得し
// 改行を<br>へ置換しDIV要素(#output)へ表示する。
var outputText = $('#input').val();
outputText = outputText.replace(/\n/g, '<br>');
$('#output').html(outputText);
// #inputの入力キーイベントをチェックし
// #outputへ表示する。
// 参考記事 http://logic-a.com/2012/05/16/jquery_textbox_realtime_getton/
$('#input').bind('click blur keydown keyup keypress change', function() {
var input = $(this).val();
input = input.replace(/\n/g, '<br>');
$('#output').html(input);
});
// テキストエリアの選択範囲をアンカー文字列としたリンクを作成。
$('#link').click(function(e) {
e.preventDefault();
var input = $('#input');
var selectedText = input.selection();
if (selectedText === '') {
return false;
}
var url = $('#url').val();
if (url === '') {
return false;
}
if (url.match('http://') !== 0) {
url = 'http://' + url;
}
$before = '<a href="' + url + '">';
$after = '</a>';
input.selection('insert', {text: $before, mode: 'before'});
input.selection('insert', {text: $after, mode: 'after'});
});
});
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>Editor</title>
<link rel="stylesheet" href="style.css" media="all">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="jquery.selection.js"></script>
<script src="editor.js"></script>
</head>
<body>
<div id="output"></div>
<textarea id="input"></textarea>
<div class="action-wrap">
<input type="button" id="link" value="リンク作成">
</div>
<div id="link-wrap">
URL: <input id="url" type="text">&nbsp;
</div>
</body>
</html>
div {
margin-top: 1em;
line-height: 1.25;
}
#output {
overflow: scroll;
width: 600px;
height: 240px;
padding: 1em;
margin-top: 1em;
padding: 0.75em;
color: #666666;
border: #EFEFEF 2px dotted;
}
textarea {
width: 600px;
height: 240px;
padding: 1em;
margin-top: 1em;
background: #EFEFEF;
line-height: 1.25;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment