WP-Mix

A fresh mix of code snippets and tutorials

Add Tweet-this with jQuery

Quick jQuery snippet today for adding a “Tweet this” button for all of your site’s pages. You can see a demo here at WP-Mix (lower-right corner).

Step 1

Upload a copy of the twitter bird (or whatever icon you wish to use), and note the image path for the next step.

Step 2

Include the following jQuery along with your other JavaScript:

// "tweet this" twitter button
$(document).ready(function(){
	var url = window.location.pathname;
	var enc = encodeURIComponent('Currently reading: https://wp-mix.com' + url + ' @perishable'); // tweet template
	var bgi = '/wp-content/themes/yourtheme/img/twitter.png'; // path to twitter icon
	$('body').append('<div id="twitter"><a id="twitter_link" href="http://twitter.com/home?status=' + enc + '" title="Share on Twitter" rel="nofollow">Tweet this!</a></div>');
	$('#twitter a').css({
		width:'36px', height:'36px', position:'fixed', bottom:'9px', right:'75px', textIndent:'-9999em', opacity: 0.7, 
		cursor:'pointer', zIndex:9999, textDecoration:'none', background:'url(' + bgi + ') no-repeat center center', 
	}).hover(function(){
		$(this).css('opacity',1.0);
	},function(){
		$(this).css('opacity',0.7);
	});
});

Almost done, just need to make a couple of edits:

  • customize the “tweet template” in the 4th line
  • Edit the “path to twitter icon” in the 5th line

Additionally, you may want to edit the CSS to suit your site’s design (lines #8 and #9).

★ Pro Tip:

Banhammer ProWizard’s SQL Recipes for WordPressSAC Pro