简体   繁体   中英

How do I fix this click function to move to a particular location slowly?

Code:

<script src="http://code.jquery.com/jquery-latest.min.js"></script>

$(document).ready(function()) {
    $('a').click(function(){
    $('html, body').animate({'scrollTop' : $($(this).attr('href')).offset().top}
    , 100000);
    return false;
})
});

On click the script is supposed to slowly move the location on the page. For some reason it's not working at all. I am new to JS so not sure what I am missing. Any ideas?

you have syntax error

$(document).ready(function() {//<<< here where having an extra `)`
    $('a').click(function(){
    var a = $(this).offset().top;// please replace `this` with the selector of the element you want to scroll to
    $('html, body').animate({'scrollTop' : a}// set the correct offset
    , 100000);
    return false;
})
});

In addition to the extraneous ) following the function parentheses (which, incidentally, closes the ready method inappropriately), causing a syntax error, there's an omitted semi-color following the parenthesis on the line below the return false statement (and yes, semi-colons are optional, but it's still a good idea not to rely on the automagical feature of JavaScript to guess where the line ends). Incidentally, I'd suggest a slight change:

//                           V- removed the extra ')'
$(document).ready(function () {
    $('a').click(function () {
        /* caching the element you want to scroll
           to (using 'getAttribute()', rather than invoking jQuery,
           to retrieve the 'href' attribute, though still wrapping into
           a jQuery object to make use of the methods */
        var target = $(this.getAttribute('href'));
        $('html, body').animate({
            'scrollTop': target.offset().top
        }, 10000);
        return false;
    }); // <-- added the semi-colon
});

JS Fiddle demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM