Reputation: 113
I have a button to share web content on Facebook on a project and when I click it doesn't works. The button just works when the users make a double click... :(
My code:
Html:
<button>
<img src = "images/socialButtons/56/facebook.png" id = "Item-A" onclick="shareFb(this.id)">
</button>
JavaScript:
function shareOnFacebook(e, id){
e.preventDefault();
FB.ui(
{
method: 'feed',
name: '',
link: 'http://anurl.com/'' + id + '.jpg',
picture: 'http://anurl.com/'+ id +'.jpg',
caption: '',
description: "",
message: ""
}
);
}
function shareFb(id){
$('#'+ id +'').click(function(e){
shareOnFacebook(e, id);
});
}
I have implemented the following script on my index.html (the button is on this file)
<!-- Facebook SDK JavaScript -->
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '#myFacebookAppIdNumber',
xfbml : true,
version : 'v2.5'
});
};
(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>
I really appreciate any help ;)
Thanks a lot.
Upvotes: 1
Views: 459
Reputation: 207511
It takes two clicks because you are attaching a click event after you click it. Why do that? Get rid of the inline click.
So add a common class:
<img class="share" id="foo" src="bar.gif" />
Attach the event to the class
$(".share").on("click", function (e) {
shareOnFacebook(e, this.id);
});
The code above needs to run at the end of your document or on document ready. You can also use event delegation instead to add just one event handler.
$(document).on("click", ".share", function (e) {
shareOnFacebook(e, this.id);
});
Upvotes: 1