Home > Enterprise >  Get text field and use it to build a Facebook sharing link
Get text field and use it to build a Facebook sharing link

Time:07-07

I am building a free utility to help mobile users share a YouTube video with a manually configured start time (YouTube does not offer this feature in their mobile website and apps).

The user pastes the link to the video and then configures the start time.

They can then copy the link to their clipboard. I have this working, with some help.

https://yttimestamp.com/

I am using this code for the copy function:

function copyFunction() {
  /* Get the text field */
  var copyText = document.getElementById("result-field");
  /* Select the text field */
  copyText.select();
  copyText.setSelectionRange(0, 99999); /* For mobile devices */
  /* Copy the text inside the text field */
  navigator.clipboard.writeText(copyText.value);
}

My next task is to create a Facebook sharing link.

It should similarly grab the current value of the "result-field" (a URL), only in this case it will generate a clickable button with an href tag that looks like this:

https://www.facebook.com/sharer/sharer.php?u=" "URL"

I imagine the resulting URL will be inserted into the following link, although perhaps I can't foresee how this function needs to be implemented as I am only a hack.

<a onclick="facebookFunction()" target="_self" href="">
<img src="img/Facebook.svg" alt="Share to Facebook"/></a>

CodePudding user response:

By default I'm hiding the link since it will not have a HREF on load. Then I set the HREF using setAttribute by calling the link by a class.

Then I have a class called active that is added to the link to display the link.

For my answer I removed your image, but you can add that back in.

function copyFunction() {
  let fbShare = document.querySelector(".facebook-share");
  fbShare.classList.remove("active");
  
  var copyText = document.getElementById("result-field");
  copyText.select();
  copyText.setSelectionRange(0, 99999); /* For mobile devices */
  navigator.clipboard.writeText(copyText.value);
  
  fbShare.setAttribute("href","https://www.facebook.com/sharer/sharer.php?u="   copyText.value);
  fbShare.classList.add("active");
}

copyFunction()
.facebook-share{display:none;}
.facebook-share.active{display:block;}
<input type="text" id="result-field" value="https://stackoverflow.com/">


<a target="_self" href="" target="_blank" >Share on Facebook</a>

  • Related