Zeshan_SE
Zeshan_SE

Reputation: 3

Automatically Scrolling a webpage with animating div

I am making a web app. I have created 25 divs.

I have Used jquery fadeIn() by which divs are gradually made and displayed one after another on screen.

But problem is that when 25 divs have been created, scroll is created due to which first 4 divs can be seen but the remaining can't be seen until user scroll the page.

I want that as one by one div is created, the page should automatically scroll to the div recently created and so on this process should be continued until the last div is created.

Upvotes: 0

Views: 129

Answers (2)

tkay
tkay

Reputation: 1726

You can use

$('html,body').scrollTop($(".answer.visible:last").offset().top);

$(function() {
  $(".answer").hide();
  $('#demo').click(function(e) {
    var _div = $('.answer[style*="display: none"]:first');
    if (_div.length) {
      _div.fadeIn();
      $('html,body').animate({
          scrollTop: _div.offset().top
        },
        'slow');
    } else {
      $(this).text('Done..!');
    }

  });
});
#demo {
  position: fixed;
  bottom: 0px;
  left: 0px;
}
.answer {
  width: 100%;
  height: 200px;
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="demo">Click here</button>
<div class="answer">1</div>
<div class="answer">2</div>
<div class="answer">3</div>
<div class="answer">4</div>
<div class="answer">5</div>
<div class="answer">6</div>
<div class="answer">7</div>
<div class="answer">8</div>
<div class="answer">9</div>
<div class="answer">10</div>
<div class="answer">11</div>
<div class="answer">12</div>
<div class="answer">13</div>
<div class="answer">14</div>
<div class="answer">15</div>
<div class="answer">16</div>
<div class="answer">17</div>
<div class="answer">18</div>
<div class="answer">19</div>
<div class="answer">20</div>
<div class="answer">21</div>
<div class="answer">22</div>
<div class="answer">23</div>
<div class="answer">24</div>
<div class="answer">25</div>

I think this looks pretty cool when we use slideDown+scrollTop. Check fiddle

Documentations

To get the coordinates http://api.jquery.com/offset/

Set vertical position of the scroll bar https://api.jquery.com/scrollTop/

Set horizontal position of the scroll bar https://api.jquery.com/scrollleft/

Upvotes: 1

rst
rst

Reputation: 2724

I found this link here smooth auto scroll by using javascript Using this you could create something like this here: http://jsfiddle.net/mrc0sp5j/

The main point is, that you create a scrolling-function using

window.scrollBy or window.scrollTo

http://www.w3schools.com/jsref/met_win_scrollto.asp With jQuery .last or .eq you can specify which element you want to scroll to

$(".mydivobjects").eq(x).position().top

Hope this helps cheers

Upvotes: 1

Related Questions