Philippe Newman
Philippe Newman

Reputation: 39

JQuery ScrollTop scrolling too far

I'm wanting to create basically a full page background image that, once the user clicks (anywhere), scrolls down to the remaining content and then hides itself. Initially, there would be no scrollbar, then once the click>scrolltop has taken place, and the background div hidden, the scrollbar appears by removing the overflow-hidden class.

My problem is that when I use the scrolltop by itself, the page does scroll directly to the element I've selected, but when I then add in the javascript code to hide the initial introduction div (on which the user clicks), the page jumps down far past the ScrollTop point.

I've included my JSFiddle link here, if anyone has any thoughts.

Upvotes: 3

Views: 4141

Answers (2)

jack blank
jack blank

Reputation: 5195

Is this helpful? After adding the hidden class you can scroll to the top of the one div.

$(function(){
  $(".intro").on("click", function(){
    $("body").removeClass("bleh");
    $("html, body").animate({
      scrollTop : $(".one").offset().top 
    }, function(){

      $(".intro").addClass("hidden")
      $(document).scrollTop(0)

    })
  })
})
html, body{
  height: 100%;
}
body{
  margin: 0;
}
.bleh{
  overflow: hidden;
}
.hidden{
  display: none;

}
.intro{
  background: red;
  text-align: center;
  padding: 20px;
  background-position: center;
  background-size: cover;
  height: 100%; 

}


.one {
  width: 100%;
  background-color: black;
  display: block;
  height: 400px;
}

.two {
  width: 100%;
  background-color: blue;
  display: block;
  height: 400px;
}
.three {
  width: 100%;
  background-color: black;
  display: block;
  height: 400px;
}

.four {
  width: 100%;
  background-color: blue;
  display: block;
  height: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<body class="bleh">
    <div class="intro">
        <h1>Click anywhere to scroll down to main content</h1>
    </div>
    
    <div class="one">
        
    </div>
    
    <div class="two">
        
    </div>
        <div class="three">
        
    </div>
        <div class="four">
        
    </div>
</body>

Upvotes: 0

J. Titus
J. Titus

Reputation: 9690

display: none is changing the height of .intro to 0, so you have two options:

Change the CSS for .hidden to use visibility: hidden

or

Change the first parameter of .animate to take into account the height of .intro: $(".one").offset().top - $(".intro").height()

I'd also suggest putting the removeClass and addClass calls in a callback function, rather than using .delay():

Example with option 2 + callback usage:

$(document).ready(function() {
  $(".intro").click(function() {
    $('html, body').animate({
      scrollTop: $(".one").offset().top - $(".intro").height()
    }, 700, function() {
      $("body").removeClass("bleh");
      $(".intro").addClass("hidden");
    });
  });
});

Upvotes: 1

Related Questions