psteinweber
psteinweber

Reputation: 813

Append "tweet this" button to blockquotes with jquery

Updated:

I'd like to append a self made "tweet this" button after blockquotes with jQuery. I figured out the following three steps are necesarry (some are already resolved thanks to the stackoverflow community):

  1. [resolved] appending anything to the blockquote
  2. [resolved] appending a working twitter share link to the blockquote
  3. making sure it works with multiple blockquotes

The code I'm using at the moment is:

<script type="text/javascript">
var completeurl = window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search;
completeurl = encodeURIComponent(completeurl);
var twshare = "https://twitter.com/share?url=" + completeurl;
var bq = $( "blockquote" ).text()

$("blockquote").append("<a href='" + twshare + "&text=" + bq + "'>Click to tweet</a>");   
</script>

So the current state is: I'm stuck at #3, making it work with multiple blockquotes per page. Ideally it wouldn't be necesarry to manually assign IDs or something similar. So fully automated one @tweet this" button per blockquote. Is that possible?

Thanks!

Upvotes: 1

Views: 559

Answers (1)

Abhitalks
Abhitalks

Reputation: 28437

Without seeing adequate markup, it is difficult to point where the problem is.

However, it works just fine.

See this fiddle: http://jsfiddle.net/JvT7h/2/

$("blockquote").append("<a href='http://twitter.com'>Click to tweet</a>");

Aside: append doesn't add an element after, but as a child inside.

Update:

As per your comments you need to customize the anchor link to be appended to multiple blockquotes depending upon the text of each blockquote.

See this updated demo fiddle: http://jsfiddle.net/abhitalks/JvT7h/3/

JQuery:

$("blockquote").each(function(){
    var $link = $("<a />"), 
        linkText = "Click to tweet",
        url = twshare + "&text=" + $(this).text();
    $link.attr("href", url);
    $link.text(linkText);
    $(this).append($link);
});

You need to iterate over all blockquotes and then use $(this) to append the customized anchor.

Upvotes: 1

Related Questions