Baivaras
Baivaras

Reputation: 438

jquery animate scroll doesn't work

I want to make scroll effect with button to my content. Maybe anyone can fix my code and explain why it is not working? Thank you !

This is my HTML :

<div class="main">
<section class="section home">
    <header>
        <div class="row">
            <div class="col-lg-12 col-md-12 col-sm-12">
                <h1>Home</h1>
            </div>
            <a href="#home-content" class="scroll">BUTTON</a>
        </div>
    </header>
    <div class="content" id="home-content">
        <p>
            My content
        </p>
    </div>
</section>
</div>

My js file: `

function scrollDown () {
        $('a[href="scroll"]').click(function(event) {
            event.preventDefault();
            var targetOffset = $('a[class="content"]').offset().top;
            $('.main').animate({
                scrollTop: targetOffset
            },1000);

        }); 
    }

`

Upvotes: 3

Views: 3843

Answers (1)

Maximillian Laumeister
Maximillian Laumeister

Reputation: 20359

Here is a demo that shows how you can cause your button to scroll the window down to your content when pressed. It adds a margin-top to your content to push it below the bottom of the viewport, so that it can showcase the scrolling action.

To get it working, I needed to remove your scrollDown function, change some of your jQuery selectors, and animate the scrollTop on html, body.

Live Demo:

$('a.scroll').click(function(event) {
    event.preventDefault();
    var targetOffset = $('div.content').offset().top;
    $("html, body").animate({
        scrollTop: targetOffset + "px"
    },1000);
});
.content {
    margin-top: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
<section class="section home">
    <header>
        <div class="row">
            <div class="col-lg-12 col-md-12 col-sm-12">
                <h1>Home</h1>
            </div>
            <a href="#home-content" class="scroll">BUTTON</a>
        </div>
    </header>
    <div class="content" id="home-content">
        <p>
            My content
        </p>
        <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eu aliquam sapien, nec accumsan odio. Nunc ac purus accumsan augue sodales malesuada ut at ipsum. Curabitur volutpat et risus ut ultrices. Fusce ante sapien, laoreet non scelerisque nec, elementum et nisl. Curabitur pharetra a sapien ac convallis. Aliquam dapibus viverra sem a lacinia. Proin tempor orci nec massa feugiat, ac tristique tellus convallis.
        </p>
    </div>
</section>
</div>

JSFiddle Version: https://jsfiddle.net/vhaye0c0/1/

Upvotes: 3

Related Questions