OnClick: Share Image on Facebook

I would like to configure the onClick function for the image on my new website that launches Facebook.

Here are some snippets of code that can help you understand what I'm talking about.

<div id="mImageBox"> <img id='my_image' src='' width="auto" height="auto"/> </div> 

The src image is empty because it is injected by another JavaScript function using "my_image"

so I tried to configure the onClick function using this method:

 <script>function fbs_click() {u=location.href;t=document.title;window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');return false;}</script> <div id="mImageBox"> <a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" onclick="return fbs_click()" target="_blank"><img id='my_image' src='' width="auto" height="auto"/></a> </div> 

The onClick function works well, however it links to the page where img is located, not img itself!

Do you have any suggestions for me?

+8
javascript css image onclick
source share
3 answers

try the following:

 <div id="mImageBox"> <img id='my_image' src='' alt='' width="auto" height="auto" onclick="fbs_click(this)"/> </div> <script> function fbs_click(TheImg) { u=TheImg.src; // t=document.title; t=TheImg.getAttribute('alt'); window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');return false; } </script> 

You do not need to use the <a> tag (the surrounding <img> tag) for the case when JS is disabled, since in this case the JS, which must enter the src attribute, also does not work.

+10
source share

Just call the function below and you can share images with your link and text on Facebook.

 function sharefbimage() { FB.init({ appId: `your appid`, status: true, cookie: true }); FB.ui( { method: `share`, name: 'Facebook Dialogs', href: $(location).attr('href'), link: 'https://developers.facebook.com/docs/dialogs/', picture: 'your image url', caption: 'Ishelf Book', description: 'your description' }, function (response) { if (response && response.post_id) { alert('success'); } else { alert('error'); } } ); 
+12
source share

Since the Facebooks JavaScript 2.9 API has been dead since last week, the above solution no longer works (I took half a day from me to find out !!!). In v2.10, the image parameter FB.ui no longer exists. But I found a workaround that creates an individual URL parameter for each image, so Facebook needs to clear the Open Graph data for each shared image separately. I shared my code in this post for reference.

0
source share

All Articles