JordanBarber
JordanBarber

Reputation: 2101

Variable not passed into jQuery scroll function

Can someone help me understand why this is not working:

   jQuery(".page-code .opening .button").click(function(event){
        event.preventDefault();
        var id = "#" + event.target.id;
        alert(id);
        jQuery('html, body').animate({
            scrollTop: jQuery(id).offset().top
        }, 500);
    })

The anchor links exist in various parts of the page, the alert is giving me proper id that I need, but the page is only scrolling a tiny bit no matter which button I click. Not sure what I'm missing here.

Upvotes: 0

Views: 62

Answers (2)

Calvin Belden
Calvin Belden

Reputation: 3114

You're setting up the destination of the scroll to be the element that was just clicked. If you want to scroll to the element that the link points to, you need to use the href attribute (assuming your buttons are a tags):

jQuery(".page-code .opening .button").click(function(event){
    event.preventDefault();
    var id = "#" + jQuery(this).attr('href');
    alert(id);
    jQuery('html, body').animate({
        scrollTop: jQuery('body').offset().top
    }, 500);
})

Upvotes: 1

molnarland
molnarland

Reputation: 16

If you would you like to do that user click to .page-code OR .opening OR .button elements then add comma to between them.

Upvotes: 0

Related Questions