0

The issue it that I can't get a simple JavaScript function to run with HTML. I get an error that says "Uncaught ReferenceError: getYear is not defined".Thanks!

$(document).ready(function () {
  function getYear(){
    document.write(new Date().getFullYear());
  }
});
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="js/script.js"></script>
</head>

<body>
    <footer>
        <p>&copy; <script> getYear()</script> | All rights reserved</p>
    </footer>
</body>
</html>
Jack Bashford
  • 38,499
  • 10
  • 36
  • 67

4 Answers4

2

I believe that's because you wrapped the function in your js file in a document.ready state so you're unable to access the function inside your HTML footer tag because of that.

removing the document.ready will solve the issue.

your new code should be

  function getYear(){
    document.write(new Date().getFullYear());
  }
Elhamy
  • 136
  • 3
1

You have to remove ready function, because this function waits that all page onload, only use:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>
     
  function getYear(){
    document.write(new Date().getFullYear());
  }

    </script>
</head>

<body>
    <footer>
        <p>&copy; <script> getYear()</script> | All rights reserved</p>
    </footer>
</body>
</html>
0

Try the following code;

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="js/script.js"></script>
</head>

<body>
    <footer>
        <p> &copy; <script>
                document.write(new Date().getFullYear());
            </script>| All rights reserved </p>
    </footer>
</body>

</html>
0

You would not need the

 $(document).ready(function () {...

Your new code should be like:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>


<script>

function getYear(){ return  new Date().getFullYear();  }

</script>

</head>

<body>
    <footer>
        <p>&copy; <script> getYear()</script> | All rights reserved</p>
    </footer>
</body>
</html>
Ehsan Kiani
  • 2,605
  • 1
  • 12
  • 18