Blackboy
Blackboy

Reputation: 21

Scroll up a div when scrolling down is finished using one button

I searched the solution on stack overflow but i didn't find. That's why i am asking the solution. I am not good in jQuery.

I am working on a site which have a functionality of scrolling down a div with a button. And i did that. Now i want when someone reached at the bottom of the div by clicking the scroll down button, the button turns into a scroll up button and takes him/her at the top of the div.

Below is my scroll down code.

<div id="testi-scroll">
   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec 
</div>

<button class="scroll-up"><img src="gotop-arrow.png" alt="gotop-arrow" /></button>

<script>
var scrolled=0;
jQuery(document).ready(function(){
jQuery(".scroll-dwn").on("click" ,function(){
    scrolled=scrolled+150;

    jQuery("#testi-scroll").animate({
            scrollTop:  scrolled
       });

});

});
</script>

Upvotes: 0

Views: 805

Answers (2)

Padawan
Padawan

Reputation: 390

I wouldn't recommend the scrolled variable being initialized to zero and updated as and when the user clicks on the button, because this approach doesn't account for the case when the user clicks and drags the scroll bar instead of using your button.

Here's how I'd tackle the problem. You can find the jsfiddle here

jQuery(document).ready(function(){
  jQuery(".scroll-btn").on('click', function(){

      if($(this).hasClass("scrollup")){
          $("#testi-scroll").animate({
              scrollTop: 0
          }, 200);
          $(this).removeClass("scrollup");
          $(this).text("Scroll Down");
      } else {
          var scrolled = $("#testi-scroll")[0].scrollTop;
          scrolled += 150;

          $("#testi-scroll").animate({
              scrollTop: scrolled
          }, 200);    

          var scrollHeight = $("#testi-scroll")[0].scrollHeight;
          var divHeight = $("#testi-scroll").height();

          if(scrolled >= scrollHeight- divHeight){
              $(this).addClass("scrollup");
              $(this).text("Scroll Up");
          }
      }
  });
});

Upvotes: 0

Paul Redmond
Paul Redmond

Reputation: 3296

Without your HTML it's hard to give a specific answer for you, but here's a suggestion: Use .toggleClass to switch classes for up and down and check if that class exists to figure out if to scroll up or down:

<script>
jQuery(document).ready(function(){
  jQuery(".scroll-btn").on('click', function(){
    jQuery(this).toggleClass('scroll-down')
    if ( jQuery(this).hasClass('scroll-down') ) { 
      $('html, body').animate({
        scrollTop: $("#element").offset().top
      }, 2000);
    } else {
      $('html, body').animate({
        scrollTop: $("#element").offset().top
      }, 2000);
    }
  });
});
</script>

Upvotes: 2

Related Questions