jQuery for a single page site that scrolls automatically after hitting a play button

617 views Asked by At

I've marked up a simple one-page site that has a absolute positioned nav-bar at the top of the page for scrolling to sections of the page using anchors. You can see my terrible code live here:

http://codepen.io/anon/pen/nlcsK

You'll also notice that there is a 'Play' div at the top of the page as what I'd really like to do is to have the page automatically scroll to different anchors at different times after you hit 'Play'.

Unfortunately, my jQuery is even worse that my HTML/CSS so I have no idea how to do this! Any (step by step) help would be much appreciated!


<nav id="nav">
  <a href="#section-one">One</a>|
  <a href="#section-two">Two</a>|
  <a href="#section-three">Three</a>|
  <a href="#section-four">Four</a>
</nav>

<div id="section-one" class="cover">
  <h1 id="play">Play</h1>
</div>

<div id="section-two" class="cover">
</div>

<div id="section-three" class="cover">
</div>

* {
  margin:0px;
  padding:0px;
  height:100%;
}

#nav {
  position:fixed; 
}

#section-one { 
  background-color:white;
}

#section-two { 
  background-color:orange;
}

#section-three { 
  background-color:grey;
}

#section-four { 
  background-color:green;
}

.cover {
  background: no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  height: 100%;
}

#play {
  width:60px;
  height:60px;
  background-color:red;
  margin: 0px auto;
}
1

There are 1 answers

0
vigonotion On

If you add this jQuery-Code:

$(document).ready(function(){
    $('a[href^="#"]').on('click',function (e) {
        e.preventDefault();

        var target = this.hash,
        $target = $(target);

        $('html, body').stop().animate({
            'scrollTop': $target.offset().top
        }, 1000, 'swing', function () {
            window.location.hash = target;
        });
    });
});

Everytime you hit a HTML anchor link the action will be overidden and jquery will scroll to it.

Same way at doing an animation for the play button. You have to get the targets position, then you can scroll to it:

$(document).ready(function() {
    $('.play').on('click', function() {
        $target = $(yourelement);
        $('html, body').stop().animate({
            'scrollTop': $target.offset().top
        }, 1000, 'swing', function () {
            window.location.hash = target;

            //do this for the next one
            $target = $(yourelement);
            $('html, body').stop().animate({
                'scrollTop': $target.offset().top
            }, 1000, 'swing', function () {
                window.location.hash = target;
                //and probably for another one here
            });
        });
    }
});

where 1000 is the time it needs to scroll in miliseconds, you can change that.