angry_kiwi angry_kiwi - 4 months ago 150
jQuery Question

how to simulate the click event on the facebook share button

I want to use jquery/js to simulate the click on original fb share button when I click my custom button.

This is what I've got:

<script>
$(function(){
// initialize fb sdk
window.fbAsyncInit = function() {
FB.init({
appId : '830561340319450',
xfbml : true,
version : 'v2.2'
});
};

(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

});
</script>
<div class="fb-share-button" data-href="www.myweb.com/topic/hello_world" data-layout="button"></div>
<button class="my_own">Lets share</button>


I want when I click on my_own, the facebook stock button also get clicked. Any idea how to do that?

Answer
  1. Remove the Facebook share button. Trying to trigger a click on it is not the way to go; it might even trigger measures they have in place to prevent click-jacking, and as a result get your app blocked by FB.

  2. Implement the call to the Share dialog when the user clicks your own button:

HTML:

<button class="my_own" type="button" onclick="share();">Lets share</button>

JavaScript:

function share() {
  FB.ui({
    method: 'share',
    href: 'http://www.myweb.com/topic/hello_world',
  }, function(response){});
}