1

I'm new in web development and I'm trying to insert the current URL into href for a Facebook share button using JS. I tried in the following way but as you can see it's not correct.

function getURL() {
    return window.location.href;
}
<div class="fb-share-button" 
    data-href="https://www.facebook.com" 
    data-layout="button" 
    data-size="small">
      <a target="_blank" 
        href="getURL()" 
        class="fb-xfbml-parse-ignore">
        Share
      </a>
</div>
Qiniso
  • 2,587
  • 1
  • 24
  • 30
S. G.
  • 11
  • 2

2 Answers2

0

try this

<script>
    document.querySelector('a').setAttribute("href",  window.location.href);
</script>


<div class="fb-share-button" data-href="https://www.facebook.com" data-layout="button" data-size="small"><a target="_blank" href="" class="fb-xfbml-parse-ignore" id='facebook-share'>Share</a></div>
Richard Price
  • 482
  • 4
  • 13
0

In your tag <a> add id

<div class="fb-share-button" data-layout="button" data-size="small"><a target="_blank" id="btnsharefb" class="fb-xfbml-parse-ignore">Share</a></div>

And create listener to event click to your tag a

document.getElementById("btnsharefb").addEventListener("click", function() {
  this.href = getURL();
});

OR add directly on load document

document.getElementById("btnsharefb").href = getURL();

E.g. https://codepen.io/darlandieterich/pen/abNrmWO

Darlan Dieterich
  • 2,369
  • 1
  • 27
  • 37