I am using the Twitter createShareButton on my site (http://conn3cted.uk.tn/quote.html) but every time the ‘New Quote’ button is pressed it creates a new twitter button, leaving me with multiple buttons (e.g. if the ‘New Quote’ button is pressed 10 times, there will be 10 share buttons).
It was working fine a couple of days ago, so not sure what the hell has happened.
My JavaScript is below
// Random Quote Generator
$(document).ready(function() {
// Set the default values for future AJAX requests
$.ajaxSetup({
// Prevent all future AJAX requests from being cached.
cache: false
});
// API URL
var quoteURL = "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1";
// getQuote function, which accepts a data parameter.
var getQuote = function(data) {
// Replace the html of the targeted element with the returned content field.
$(".quoteContent").html(data[0].content);
// Replace the html of the targeted element with the returned title field.
$(".quoteTitle").html('Author: ' + data[0].title);
newColor();
twttr.ready(function() {
// Use the pre-made createShareButton function
twttr.widgets.createShareButton(
// Do not share a URL
" ",
// Div where the share button should be inserted
document.getElementById('tweetButton'),
{
// Define the tweet that will be used
text: "'" + $(".quoteContent").text().replace(/(rn|n|r)/gm,"") + "'n" +
$(".quoteTitle").text(),
// Set the size of the Twitter share button
size: "large",
}
);
});
};
var newColor = function() {
var color = Please.make_color();
$("body, button, .btn").css("background-color",color);
$("p, blockquote").css("color",color);
};
/*
* On every page load get JSON data from the URL, defined in the
* 'url' variable, and then run the getQuote function
*/
$.getJSON(quoteURL, getQuote);
//newColor();
/*
* When the button is clicked load get JSON data from the * URL,defined in the 'url' variable, and then run the
* getQuote function.
*/
$(".regenButton").click(function() {
$.getJSON(quoteURL, getQuote);
});
});
3
Answers
For anybody that comes across this post; I was looking into this a bit more and discovered a way to create the Twitter Share button without using the Twitter Widget.
First you need to create an A tag...
And then setup jQuery to amend it for each new quote...
Your twitter share button code is inside the
getQuote
function – so each time.regenButton
is clicked,getQuote
is called, giving you another button.It’s because you create the twitter button in your
$.getJSON
success callback. So everytime a quote is loaded, a twitter button is created.The best solution would be to create the button once, and update the share text everytime a quote is loaded. Which I can’t find in the docs. So my best guess is to delete the previously one first: