Return current URL for a share button

1.2k Views Asked by At

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>

2

There are 2 best solutions below

1
On

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>
0
On

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