I can't copy the generated link directly (without ctrl+C) I am usign document.execCommand('copy') but it seems it has no effect. If code has no AJAX then its working pefectly. Here's the
HTML:
<div class="permalink-control"> </div> JQUERY:
$(".permalink-control") .append( '<div class="input-group">' + ' <span class="input-group-btn"><button type="button" class="btn btn-default" title="Get Permalink"><span class="glyphicon glyphicon-link"></span></button></span>' + ' <input type="text" class="form-control">' + '</div>' ); $(".permalink-control input") .hide() .focus(function () { // Workaround for broken selection: https://stackoverflow.com/questions/5797539 var $this = $(this); $this.select() .mouseup(function () { $this.unbind("mouseup"); return false; }); }); $(".permalink-control button") .click(function () { var $this = $(this); $.ajax({ url: "https://api-ssl.bitly.com/shorten", dataType: "jsonp", data: { longUrl: window.location.href, access_token: "your access token", format: "json" }, success: function (response) { var longUrl = Object.keys(response.results)[0]; var shortUrl = response.results[longUrl].shortUrl; if (shortUrl.indexOf(":") === 4) { shortUrl = "https" + shortUrl.substring(4); } $this.parents(".permalink-control") .find("input") .show() .val(shortUrl) .focus(); }, async:false }); }); UPDATE:
How do I copy to the clipboard in JavaScript?
is not answer to my question as My code also copies without using ctrl+C if AJAX is not there. However when I am using AJAX document.execCommand('copy') is not working.
$.ajax()on each page load, set up a larger invisible element around the button and trigger the ajax on mouse-entering the invisible element. Not bullet proof, but better than nothing. A good trick might be to have the button in a dropdown, drawer, popup, modal or tooltip. When the user opens it, get the response before it opens up. And disable the button before ajax gets back.