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.

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(
	'
\n'+ '\n'+ '\n'+ '\n' ); $.getScript('https://apis.google.com/js/plusone.js'); $.getScript("https://platform.twitter.com/widgets.js"); $(this).off('click'); });

Your thoughts? Click here to comment.

Comment

All fields voluntary.
Comment submission rules apply.