Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: Uncaught ReferenceError: function is not defined

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?

like image 779
Dmitry G Avatar asked Jan 18 '26 16:01

Dmitry G


2 Answers

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>
like image 76
MrCode Avatar answered Jan 21 '26 06:01

MrCode


You have to put back_to_top outside the jquery document ready function

like image 26
sbaglieri Avatar answered Jan 21 '26 07:01

sbaglieri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!