0

I get error in console on line getUrlVars() {

Uncaught SyntaxError: Unexpected token {

<!DOCTYPE html>
<html>

<head>
<script>

document.getElementById('myelement').onclick = function() {
    function getUrlVars() {
        var url = window.location.href;
        console.log(url.substring(url.indexOf('?')));
    }
}

</script>
</head>

<body>

<a id="myelement" href="#">some link</a>

</body>
</html>

How to fix it?

j-pepper
  • 1
  • 1

3 Answers3

0

If this is your actual code, then note this: you have not placed the "end of command line marker" ; in the getUrlVars() end, and neither on the document.getElementById('myelement').onclick line. Also, you are creating a function that creates a function, and that is un-necessary.

Try this:

document.getElementById('myelement').onclick = function() {
       var url = window.location.href;
       console.log(url.substring(url.indexOf('?')));
};
Bonatti
  • 2,778
  • 5
  • 23
  • 42
0

please try the below JS,

window.onload = function() {
    document.getElementById('myelement').onclick = function getUrlVars() {
      var url = window.location.href;
      console.log(url.substring(url.indexOf('?')));
    }
  }

Changes:

a) will do any action after window load is complete

b) function getUrlVars is the function when click happens on the anchor tag

Here comes a fiddle LINK

Oxi
  • 2,918
  • 17
  • 28
0

This is a small JS that allows you to get a parameter from the queryString based on the name.

<script>
    var getUrlParameter = function getUrlParameter(sParam) {
        var sPageURL = decodeURIComponent(window.location.search.substring(1)),
                sURLVariables = sPageURL.split('&'),
                sParameterName,
                i;

        for (i = 0; i < sURLVariables.length; i++) {
            sParameterName = sURLVariables[i].split('=');

            if (sParameterName[0] === sParam) {
                return sParameterName[1] === undefined ? true : sParameterName[1];
            }
        }
    };
</script>

How to use the script for a parameter:

<script>
    $(document).ready(function(){
        if(getUrlParameter("numeParametru "))
          alert(getUrlParameter("ParameterName"));
          var myParam = getUrlParameter("ParameterName");
          //do stuff;
    });
</script>

Like this, if the parameter exists, you can do whatever you would like to with it.

Simply Me
  • 1,579
  • 11
  • 23