Skip to content

Instantly share code, notes, and snippets.

@kenzo0107
Last active March 10, 2016 02:41
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 kenzo0107/88af2f3e961324fac815 to your computer and use it in GitHub Desktop.
Save kenzo0107/88af2f3e961324fac815 to your computer and use it in GitHub Desktop.
# [bitly Generic Access Token] は https://bitly.com/a/oauth_apps より 生成してください。
#
# 以下のようなinputボックスを想定しています。
# <input type="text" name="hogehoge" value="" class="bitly">
var generateUrl = (function () {
// 短縮化するURLの文字列数. 以下の場合30文字未満の場合短縮化しない。
var SHORTEN_URL_LENGTH = 30;
// フォームから値を取得
function getUrl() {
$(".bitly").on("keyup", function () {
var btnOnkeyup = $(this);
var url_val = btnOnkeyup.val();
if (url_val.length < SHORTEN_URL_LENGTH) {
return;
}
// 結果を表示
convertBitly(url_val, 'bitly.com').done(function (d) {
if (d.data.url) {
btnOnkeyup.val(d.data.url);
}
});
});
}
// Bitly APIにリクエスト
function convertBitly(url, domain) {
var encUrl = encodeURIComponent(url);
console.log('encUrl = ' + encUrl);
var bitly = "https://api-ssl.bitly.com/v3/shorten?access_token=[bitly Generic Access Token]&longUrl=" + encUrl + "&domain=" + domain;
var d = new $.Deferred();
$.ajax({
type: "get",
url: bitly,
dataType: "jsonp",
processData: false,
contentType: false,
success: d.resolve,
error: d.reject
});
return d.promise();
}
return {
init: function () {
getUrl();
}
};
} ());
$(document).ready(function () {
generateUrl.init();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment