Can't get tweet button to look like a button, Random Quote machine

Can't get tweet button to look like a button, Random Quote machine
0

#1

I’m almost done with the random quote machine project. My problem is after you click a button to get a quote, the Tweet button turns into a hyperlink, underlined blue text.

The tweet button looks like a button, blue with the bird, before you click “Get Message”, but after you get your quote the button looks bad. I’d like it to look nice.

Here’s the HTML that sets up the button.
<div id="share-button"> <a class="twitter-share-button" href="https://twitter.com/intent/tweet?text=Hello%20world" data-size="large"> Tweet</a> </div>

When a user click’s “Get Quote”, a jQuery .html function runs and should insert new code into the div with id share-button and it does that except for carrying over the data-size="large" bit somehow, I believe. I don’t know why.

My jQuery (i did a lot of += because I was having trouble getting the whole string I wanted to concatenate in one line, like with +s, I don’t know why).
var tweet = '<a class="twitter-share-button" href="https://twitter.com/intent/tweet?text='; tweet += json.quoteText; tweet += " -"; tweet += author; tweet += '" '; tweet += 'data-size="large">Tweet</a>'; $("#share-button").html(tweet);

I did add the javascript from https://platform.twitter.com/widgets.js via “Settings”, which I think helped the Twitter button look like a Twitter button to start out with.

You can see the Pen at http://codepen.io/whosyerricky/full/BzRzbY/


#2

If you use the developer tools in your browser, you’ll see that Twitter’s javascript is inserting a bunch of extra elements into your share-button div. So, when you use $("#share-button").html(), you’re replacing all of those elements with a single anchor tag.

One option would be to target the anchor tag directly, and then just change the href attribute. For example:

let tweet = "https://twitter.com/intent/tweet?text=" + json.quoteText + " -" + author;
$("#share-button a").attr('href', tweet);

#3

Actually, that solution isn’t workable, because the Twitter javascript is loading an iframe from a different domain, and you will not be allowed to modify it with jQuery according to this Stack Overflow. Since the Twitter script is controlling the button, you may have to change the target using their API. Or else just build the button yourself using the Web Intent API, and abandon the Twitter script.


#4

Thank you. I did try the first solution but couldn’t get it to work. I’ll have to look through the Web Intent API documentation.


#5

Works like a charm, I spent two days trying to figure it out window.open is disable in codepen, it worked fine in my local environment, but in codepen, man it drove me half mad. Thanks a lot.