Reputation: 177
I am building a Random quote machine. I have a tweet button to share the quote. It works, but only after I click "Generate Quote" button first. If I click "tweet" straight after the page is loaded - it doesn't work.
I know it is happening because my $(".twitter-share-button").attr("href", "https://twitter.com/intent/tweet?text=" + thisQuote);
code is within the $("#gen").on("click", function(){
, but I don't know how to remove it outside this function.
When I place it outside it doesn't work, because the value to the thisQuote
var is passed within $("#gen").on("click", function(){
When I try to put all the code before $("#gen").on("click", function(){
it stops working.
How do I order the functions properly in this case?
My pen: http://codepen.io/s4ek1389/pen/zZGNWw?editors=1010
$(document).ready(function(){
var thisQuote = "";
$("#gen").on("click", function(){
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(json) {
var author = "";
var quote = "";
$.ajaxSetup({cache:false});
json.forEach(function(val){
author+= val.title;
quote+= val.content;
var shortQuote = quote.slice(3,-5);
thisQuote = shortQuote + " - " + author;
$("#author").html(author);
$("#mainquote").html(quote);
})
$(".twitter-share-button").attr("href", "https://twitter.com/intent/tweet?text=" + thisQuote);
});
});
});
Upvotes: 0
Views: 44
Reputation: 2140
You have to retrieve the random quote when the page is finished loading instead of only when the button is clicked.
I've made a separated method so it's easier to read and maintain.
Try this:
$(document).ready(function () {
var thisQuote = "";
getRandomQuote();
$("#gen").on("click", function () {
getRandomQuote();
});
function getRandomQuote() {
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function (json) {
var author = "";
var quote = "";
$.ajaxSetup({ cache: false });
json.forEach(function (val) {
author += val.title;
quote += val.content;
var shortQuote = quote.slice(3, -5);
thisQuote = shortQuote + " - " + author;
$("#author").html(author);
$("#mainquote").html(quote);
})
$(".twitter-share-button").attr("href", "https://twitter.com/intent/tweet?text=" + thisQuote);
});
}
});
CodePen:
http://codepen.io/anon/pen/PpzvvP
Upvotes: 1
Reputation: 2118
You can trigger a click the first time to assign the href to your "tweet button"
$("#gen").trigger("click");
http://codepen.io/sassoli/pen/yMJWZo
if you need to start with the default sentence of William Shakespeare, instead you can add this
http://codepen.io/sassoli/pen/OpXYGM
$(".twitter-share-button").attr("href", "https://twitter.com/intent/tweet?text=" + $("#mainquote").text()+ " - "+ $("#author").text());
Upvotes: 1