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>© <script> getYear()</script> | All rights reserved</p>
</footer>
</body>
</html>
4 Answers 4
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());
}
Comments
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>© <script> getYear()</script> | All rights reserved</p>
</footer>
</body>
</html>
Comments
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> © <script>
document.write(new Date().getFullYear());
</script>| All rights reserved </p>
</footer>
</body>
</html>
Comments
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>© <script> getYear()</script> | All rights reserved</p>
</footer>
</body>
</html>
getYearfunction creates only after the document is ready. Move the function declaration outside thereadycallback