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?
It'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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With