2

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?

3 Answers 3

7

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>
Sign up to request clarification or add additional context in comments.

Comments

2

You have to put back_to_top outside the jquery document ready function

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.