george george - 6 months ago 11
Javascript Question

issue with link to external js file

I have a problem with the

document.ready
function. I put my external
.js
link at the bottom but trigger function on the top and I get this error:


Uncaught ReferenceError: scrollWin is not defined


Is there any possibility to add the link to
.js
file in the bottom, or do I have to put it in the
<head>
?

<head>
<link href="css/main.css" rel="stylesheet">
</head>
<body>

<button onclick="scrollWin()">Click me to scroll</button>

<script src="js/jquery-1.12.3.js"></script>
<script src="js/custom.js"></script>
</body>


The JavaScript file:

// custom.js file
$(document).ready(function() {

function scrollWin() {
window.scrollTo(300, 500);
}

});

Answer

define function outside on document.ready

$(document).ready(function() {

});

 function scrollWin() {
     window.scrollTo(300, 500);
 }

OR

$(document).ready(function(){
  scrollWin = function ()
  {
     window.scrollTo(300, 500);
  }
});
Comments