0

I have this fairly simple function that I want to call with onclick="". No matter what I do, I get the error Function is not defined.

html:

<a href="#" onclick="shareURL(); return false;" data-share="https://www.facebook.com/sharer/sharer.php?u=" href="#">Share on Facebook</a>

js:

function shareURL() {
  var $url = window.location.href;
  var $src = $(this).data("share");
  $url = encodeURI($url);
  if ($src) {
    window.location.href = $url + $src;
  }
}

The function resides inside document ready, like in this Fiddle.

Meek
  • 3,086
  • 9
  • 38
  • 64
  • Try it like this, then it works.https://jsfiddle.net/3vwc0sp2/8/ – Carsten Løvbo Andersen Nov 26 '18 at 08:54
  • Have you add jquery ? – Sfili_81 Nov 26 '18 at 08:54
  • In your fiddle, you have `on ready` wrapper, change to `no-wrapper - head` – Justinas Nov 26 '18 at 08:55
  • 2
    Read up on `scope`. Your `shareURL` function is *only defined* within the scope of document.ready - it's not visible outside that scope, it not visible to `onclick=`. If you used jquery to wire-up the events as recommended, then this would also happen inside the doc.ready so would find the function as they are in the same scope. – freedomn-m Nov 26 '18 at 08:58

1 Answers1

3

You have to put your shareURL Method outside of the $(document).ready{function()}, please consider following examples for more details.

below example works fine as i have put shareURL Method outside of the document.ready method

function shareURL() {
  var $url = window.location.href;
  var $src = $(this).data("share");
  $url = encodeURI($url);
  console.log("method called!");
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" onclick="shareURL(); return false;" data-share="https://www.facebook.com/sharer/sharer.php?u=" href="#">Share on Facebook</a>

below will not work as scope of share url is limited to document.ready method

$(document).ready(function(){
  function shareURL() {
    //this will not work as scope of the function is limited to document
    var $url = window.location.href;
    var $src = $(this).data("share");
    $url = encodeURI($url);
    console.log("this method will never called and gives you error Uncaught ReferenceError: shareURL is not defined");
    if ($src) {
      window.location.href = $url + $src;
    }
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" onclick="shareURL(); return false;" data-share="https://www.facebook.com/sharer/sharer.php?u=" href="#">Share on Facebook</a>
Dhaval Pankhaniya
  • 1,996
  • 1
  • 15
  • 26