Please help me to refresh a single html element after the initial page load. What my program should do in basic terms: (FreeCodeCamp exercise: Random Quote Machine)
I have succeeded in making everything work as it should but I find that my anchor element that I use to send the tweet will not refresh after the initial page load. Its "data-text" attribute has changed accordingly but it does not reflect so on the button/link.
This is an extract from my html body: full code at http://codepen.io/jattas/pen/gmNQpv
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<div class="button-box">
<button id="getQuote">Generate new quote</button>
<a href="https://twitter.com/share" class="twitter-share-button" data-text="" data-show-count="false">Tweet</a>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
</div>
I need the anchor element to refresh in order to display the newly changed attribute and not the one from the initial page load. Please help! I'm sure this is not supposed to be so difficult.
This is the relevant extract from my javascript:
var textToTweet = '';
function processQuote() {
var currentQuote = obj.quote;
var currentAuthor = obj.author;
$(".quote").html(currentQuote);
$(".author").html("- " + currentAuthor);
textToTweet = currentQuote + " " + "-" + currentAuthor;
$(".twitter-share-button").attr("data-text", textToTweet);
alert($(".twitter-share-button").attr("data-text")); //this is to confirm that the "data-text" attribute has changed as planned
}
$(document).ready(function() {
processQuote();
$("#getQuote").on("click", function() {
getQuote();
processQuote();
});
});
Many thanks.
I found a work-around to this problem thanks to Danyx's answer to this question.
Morfium's solution above does work but it created additional buttons which were difficult to place where needed.
Instead, as per Danyx's solution, do not create the button in html. Rather create it in a function that runs each time a new quote is created:
function createButton() {
$(".twitter-share-button").remove(); //this does nothing during the first run but is required in order to prevent creating duplicate buttons
var button = document.createElement('a');
button.classList += "twitter-share-button";
button.innerHTML = "Tweet";
button.setAttribute("data-text", textToTweet);
button.setAttribute("data-url", " "); //removes unwanted codepen url at end of tweet
button.setAttribute("data-via", "");
button.setAttribute("href", "https://twitter.com/intent/tweet");
document.querySelector(".button-box").appendChild(button);
twttr.widgets.load(); //this reloads the twitter widget (https://dev.twitter.com/web/javascript/loading) that I failed to mention in my original question - more info on this in Danyx's answer mentioned above
}
The full code can be seen here.