Reputation: 317
I am looking for a JQuery solution to automatically scroll to the first anchor point on a page on only the first scroll action.
The opening of the website is a full screen video with a down arrow letting the user know they can scroll down for more sections. If the user uses the scroll wheel, I want it to instantly slide down to the first section and after that it can go back to normal scrolling.
Is there a possible solution for this?
Upvotes: 2
Views: 4581
Reputation: 73251
You can set a flag and only perform the action if it is false and set it to true on first scroll:
window.wasScrolled = false;
$(window).bind('scroll',function(){
if (!window.wasScrolled){ $('html, body').animate({scrollTop:document.getElementById('to').getBoundingClientRect().top},1000)}
window.wasScrolled = true;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="height:4000px"></div>
<div id="to" style="background:black;height:10000px"></div>
Upvotes: 3
Reputation: 858
jQuery has a one() method for executing a bound function a single time.
$('.scroll').one('scroll', function(e) {
// jump to section
// window.location.hash = 'section';
alert('jumping to #section');
});
.scroll {
height: 100px;
border: 1px solid red;
overflow: auto;
}
.scroll div {
height: 1000px;
border: 1px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scroll">
<div>
scroll me
<br><br><br><br><br><br><br><br><br><br><br><br>
<a id="section" name="section">first section</a>
</div>
</div>
Upvotes: 1
Reputation: 5468
Get the y position of the first 'A' element with a 'Name' attribute (bookmark) then scroll to that position with an animation then Unbind the Scroll event so it does not trigger again.
$(window).scroll(function(e){
var destination = $('a[name]').offset().top;
//jQuery UI needed for animate function
$("html,body").animate({scrollTop: destination}, 600, "easeOutExpo", function(){});
unbindScroll();
});
function unbindScroll(){
$(window).unbind("scroll");
}
See http://jsfiddle.net/sjmcpherso/ct3vkkr0/
Upvotes: 1