Dynamically Changing Data-text On Twitter Widget
Solution 1:
The twitter widget load asynchronously.
Loading the widgets.js file asynchronously will require you to wait before binding events
No matter your code is before or after the load widget line,
twttr.widgets.load(document.getElementById("tweet"));
you have to wait that the widget is loaded.
Try this code
twttr.ready(
function (twttr) {
twttr.events.bind(
'loaded',
function (event) {
var text = quote[0].content.substring(3, quote[0].content.length - 5);
document.querySelector("#quote").innerHTML = text;
document.querySelector(".twitter-share-button").setAttribute("data-text", text);
}
);
}
);
Solution 2:
I found a way to do it, here's what you need to know:
1) There's no need to have a twitter button in the initial HTML (this will only create a duplicate button that you'll need to delete later).
2) Simply create the button
var button = document.createElement('a');
button.classList += "twitter-share-button";
button.innerHTML = "Tweet";
button.setAttribute("data-text", text);
button.setAttribute("data-via", via);
button.setAttribute("href", "https://twitter.com/intent/tweet");
And append it wherever you want it to be
document.querySelector(".quote").appendChild(button);
After that all you need to do is reload the widget
twttr.widgets.load();
Since it loads asynchronously I don't know whether or not it's necessary to check before calling the load method, I've been reloading for a few minutes and haven't found any issues with it, keep this in mind if your button isn't loading properly.
Post a Comment for "Dynamically Changing Data-text On Twitter Widget"