I have this code:
<script>
$(function () {
function back_to_top(){
$('body,html').animate({scrollTop: 0}, 100);
}
});
</script>
<div class="toTop" onClick="back_to_top();">To up!</div>
When I click to this button, chrome show me this error: Uncaught ReferenceError: back_to_top is not defined. Where is my mistake?
I have this code:
<script>
$(function () {
function back_to_top(){
$('body,html').animate({scrollTop: 0}, 100);
}
});
</script>
<div class="toTop" onClick="back_to_top();">To up!</div>
When I click to this button, chrome show me this error: Uncaught ReferenceError: back_to_top is not defined. Where is my mistake?
Share Improve this question asked Feb 23, 2015 at 13:58 Dmitry GDmitry G 931 silver badge8 bronze badges3 Answers
Reset to default 7It's because the jQuery DOM ready function creates a new scope, enclosing your function, which means it's not accessible from the global scope. Inline events must be in the global scope.
function back_to_top(){
$('body,html').animate({scrollTop: 0}, 100);
}
$(function () {
});
Or drop the inline handler and use unobtrusive JavaScript.
$(function () {
function back_to_top(){
$('body,html').animate({scrollTop: 0}, 100);
}
$('.toTop').click(function(){
back_to_top();
});
});
HTML with no inline handler:
<div class="toTop">To up!</div>
You have to put back_to_top outside the jquery document ready function
JavaScript has function scope. That means that variables (including function declarations) defined within a function, will only be available in that function.
i.e. in this case back_to_top
is only accessible within the $(function(){...})
.
...onClick="back_to_top();"
is looking at the global scope and back_to_top
is not available. You can expose it though if you do something like this:
$(function () {
window.back_to_top = function {
$('body,html').animate({scrollTop: 0}, 100);
}
});
I don't think this is ideal but it will work in your case. A better way is to attach a listener. Have a look at jQuery click method.
Hope it helps.