Jquery Detect Click Facebook Like Button Today

Social media integrations are great, but debugging them can be a nightmare. One of the most common questions I see is: "How can I run custom code when a user clicks the Facebook Like button?"

// This will NOT work $('#facebook-like-button').on('click', function() alert('Liked!'); ); The Like button resides in a cross-origin iframe. jQuery cannot see inside it for security reasons. Facebook provides its own event system. When someone clicks "Like" (Facebook calls this creating an "edge"), the SDK fires an event you can listen for. Step 1: Load the Facebook JavaScript SDK Make sure the SDK is loaded on your page. jquery detect click facebook like button

$(document).ready(function() // Listen for the 'edge.create' event window.fbAsyncInit = function() FB.Event.subscribe('edge.create', function(href, widget) // href = the URL that was liked console.log('User liked: ' + href); // Your custom jQuery code here alert('Thanks for liking!'); $('#like-message').fadeIn(); ); // Also detect when someone unlikes (optional) FB.Event.subscribe('edge.remove', function(href, widget) console.log('User unliked: ' + href); ); ; ); The fbAsyncInit function must be defined before the SDK loads. If you load the SDK asynchronously (as shown above), this pattern works perfectly. Social media integrations are great, but debugging them