in Web Development

Social Buttons Only When a Visitor Wants Them Using jQuery

I haven’t posted in a while so I thought I share the method I’ll be using in future to call social media buttons (Google +1, Twitter, and Facebook Like). I had (and currently still have) the problem that each time a visitor comes to my site that their visit is being tracked by all the social media button vendors in the guise of a feature. By using the magic of HTML5 (data-* attributes) and jQuery I found a solution that should be simple to implement in any new templating system I use. It allows the code for the social media buttons to load only if someone actually wants to share that information, which I feel is a nice compromise between removing them altogether and retaining them as is. The code is posted below.

Update 2013-08-13: I’ve changed the code a little, including a reddit button, using quotes properly and adding IDs to the iframes so they work in current versions of IE when there’s more than one set of these buttons.

Update 2025-08-07: Removed Google+ button, modified code to display correctly, updated the jQuery library referenced. The reddit button needs redoing so it’s been commented out, I’ll get to fixing that later.

HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>

<body>

<div class="social-field" data-share-url="http://example.com" data-share-title="Example Domain" >Want to share what you've read? Click this to load buttons.</div>

<script src="social-media-buttons.js"></script>

</body>
</html>

JavaScript (social-media-buttons.js)

// Puts social buttons in .social-field when clicked - needs to be at end of document
$(".social-field").on('click', function(){
	var $share_url = $(this).data("share-url");
	var $share_title =  $(this).data("share-title");
	var $share_id = $share_title.toLowerCase().replace(/ /g, '-'); 
	$(this).empty();
	$(this).append(
	'<a href="https://twitter.com/share" class="twitter-share-button" data-url="'+$share_url+'" data-text="'+$share_title+'" data-count="horizontal">Tweet</a>\n'+
	'<iframe id="'+$share_id+'-fb" src="https://www.facebook.com/plugins/like.php?href='+$share_url+'%2F&layout=button_count&show_faces=true&width=300&action=like&font&colorscheme=light&height=21" style="border-style:none; overflow:hidden; width:85px; height:21px;"></iframe>\n'//+
//	'<iframe id="'+$share_id+'-reddit" src="https://www.reddit.com/static/button/button1.html?width=120&url='+$share_url+'" style="border-style:none; overflow:hidden; width:120px; height:22px;" ></iframe>\n'
	);
	$.getScript("https://platform.twitter.com/widgets.js");
	$(this).off('click');
	});

Your thoughts? Click here to comment.

Comment

All fields voluntary.
Comment submission rules apply.