I'm trying to make a browser scroll to a point on a page if the page is scrolled down. I'm using jQuery .bind() to bind html to mousewheel. Here's my code:
"use strict";
var scrollpoint = 1;
$(document).ready(function(){
console.log(scrollpoint);
$("#divacon").hide();
$("#divbcon").hide();
$('#div-a').waypoint(function() {
$("#divacon").fadeIn();
var scrollpoint = 2;
console.log("waypoint a reached");
},{context:"#container"});
$('#div-b').waypoint(function() {
$("#divbcon").fadeIn();
console.log("waypoint b reached");
},{context:"#container"});
and
$('html').bind('mousewheel', function(e){
var flag = true;
if(flag) {
if(e.originalEvent.wheelDelta < 0) {
if((scrollpoint == 1)) {
var target = $('#div-a');
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
var targetoffset = target.offset().top;
console.log(scrollpoint);
$('#container').animate(
{scrollTop: targetoffset},
400,
function(){
var scrollpoint = 2;
console.log(scrollpoint);
}
);
}
else if((scrollpoint = 2)){
//scroll down
console.log('2');
}
else{
//scroll down
console.log('Down');
}
}else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
flag = false;
}
});
What's happening is that my if statement is being called after the first time, even when flag = false;. What am I doing wrong? The site can be found live at http://wilsonbiggs.com/sandy
I think it has to be
var flag = true; //put the flag out side mouse wheel bind.
$('html').bind('mousewheel', function(e){
if(flag) {
Otherwise each time your even triggers you set flag to true and the following if condition will be satisfied always.
Related
I have a script which has a button to scroll the site but I need it to scroll automatically on page load. I need the script to scroll exactly like shown below, except the button. Could anyone change it for me? I'm new to javascript, thanks..
function scroll(element, speed) {
var distance = element.height();
var duration = distance / speed;
element.animate({scrollTop: distance}, duration, 'linear');
}
$(document).ready(function() {
$("button").click(function() {
scroll($("html, body"), 0.015); // Set as required
});
});
Call the scroll function in on window load, this will scroll the page on load finished.
$(window).on('load', function(){
scroll($("html, body"), 0.015); // Set as required
})
You can try the below JavaScript code
var div = $('.autoscroller');
$('.autoscroller').bind('scroll mousedown wheel DOMMouseScroll mousewheel keyup', function(evt) {
if (evt.type === 'DOMMouseScroll' || evt.type === 'keyup' || evt.type === 'mousewheel') {
}
if (evt.originalEvent.detail < 0 || (evt.originalEvent.wheelDelta && evt.originalEvent.wheelDelta > 0)) {
clearInterval(autoscroller);
}
if (evt.originalEvent.detail > 0 || (evt.originalEvent.wheelDelta && evt.originalEvent.wheelDelta < 0)) {
clearInterval(autoscroller);
}
});
var autoscroller = setInterval(function(){
var pos = div.scrollTop();
if ((div.scrollTop() + div.innerHeight()) >= div[0].scrollHeight) {
clearInterval(autoscroller);
}
div.scrollTop(pos + 1);
}, 50);
here on the load of the page. The text are auto-scrolled upto the end of the page.
I've put in a html several divs with IDs in a row prepended with the letter d, e.g: #d1, #d2, #d3... Then i created the javascript code below:
var pos = 0;
$("#button-up").on('click', function(e) {
e.preventDefault();
if(pos > 1){
pos -= 1;
$("html, body").stop().animate({
'scrollTop': $("#d"+pos).offset().top-300},200,"swing");
};
});
$("#button-down").on('click', function(e) {
e.preventDefault();
if(pos < 10){
pos += 1;
$("html, body").stop().animate({
'scrollTop': $("#d"+pos).offset().top-300},200,"swing");
};
});
window.addEventListener("scroll", function(event) {
var posi = this.pageYOffset;
if(posi-(pos-1)*1070+50 >= 1070){pos += 1} else if((pos-1)*1070+50-posi <= -1070){pos -= 1};
});
Finally my site scrolls down when i click the button-down, but i need to click twice the button-up for it scrolls up. Why? Is there a better way than this that gets the expected result?
I made it work changing this part:
window.addEventListener("scroll", function(event) {
var posi = this.pageYOffset;
if(posi-(pos-1)*1070+50 >= 1070){pos += 1} else if((pos-1)*1070+50-posi <= -1070){pos -= 1};
});
with this one:
window.addEventListener("mousewheel", function(e) {
e.preventDefault();
console.log('passou por 6');
var evt = window.event || e //equalize event object
evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible
var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF
if(delta > 0) {
if(pos > 1){
console.log('passou por 3');
pos -= 1;
$("html, body").stop().animate({
'scrollTop': $("#d"+pos).offset().top-300},200,"swing");
};
//scroll up
console.log('cima');
}
else{
if(pos < 10){
pos += 1;
$("html, body").stop().animate({
'scrollTop': $("#d"+pos).offset().top-300},200,"swing");
};
console.log('baixo');
//scroll down
};
});
Use jquery scoll function
$(window).scroll(function(event){
// your code
});
I'm using a smooth scroll script for a site I'm currently working on, and I've got a really annoying problem what I've experienced before with the same script. It works nice and smoothly but when I click on one of the navigation points what should lead me to the div(or a) I'm trying to target, it shows me the targeting area for like 0.1 seconds, and then it starts to scroll. It doesn't happen everytime, but often enough to be annoying. How could I prevent this? Here is the script I'm talking about:
$(window).load(function(){
$(".contactLink").click(function(){
if ($("#contactForm").is(":hidden")){
$("#contactForm").slideDown("slow");
}
else{
$("#contactForm").slideUp("slow");
}
});
});
function closeForm(){
$("#messageSent").show("slow");
setTimeout('$("#messageSent").hide();$("#contactForm").slideUp("slow")', 2000);
}
$(window).load(function() {
function filterPath(string) {
return string
.replace(/^\//,'')
.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
.replace(/\/$/,'');
}
$('a[href*=#]').each(function() {
if ( filterPath(location.pathname) == filterPath(this.pathname)
&& location.hostname == this.hostname
&& this.hash.replace(/#/,'') ) {
var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : true;
if ($target) {
var targetOffset = $target.offset().top - 110;
$(this).click(function() {
$('html, body').animate({scrollTop: targetOffset}, 1400);
var d = document.createElement("div");
d.style.height = "101%";
d.style.overflow = "hidden";
document.body.appendChild(d);
window.scrollTo(0,scrollToM);
setTimeout(function() {
d.parentNode.removeChild(d);
}, 10);
return false;
});
}
}
});
});
setTimeout(function() {
d.parentNode.removeChild(d);
}, 10);
return false;
});
move the return false out of the setTimeOut
Found the solution:
$(this).click(function(e) {
e.preventDefault();
Now it rolls fine.
So I want to fire a function only once every time a user scrolls up or down via the Mousewheel. See: jsFiddle Demo. The issue is that even though I have the e.preventDefault(), the function still fires multiple times.
The goal is for the function to fire only once whenever a user scrolls up or down. Similar to this site.
Here is the code that I have so far:
var sq = {};
sq = document;
if (sq.addEventListener) {
sq.addEventListener("mousewheel", MouseWheelHandler(), false);
sq.addEventListener("DOMMouseScroll", MouseWheelHandler(), false);
} else {
sq.attachEvent("onmousewheel", MouseWheelHandler());
}
function MouseWheelHandler() {
return function (e) {
var e = window.event || e;
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
if (delta < 0) {
/* Scroll Down */
e.preventDefault();
console.log("Down. I want this to happen only once");
} else {
/* Scroll Up */
console.log("up. I want this to happen only once");
e.preventDefault();
}
return false;
}
return false;
}
This has helped me:
var isMoving=false;
$(document).bind("mousewheel DOMMouseScroll MozMousePixelScroll", function(event, delta) {
event.preventDefault();
if (isMoving) return;
navigateTo();
});
function navigateTo(){
isMoving = true;
setTimeout(function() {
isMoving=false;
},2000);
}
Basically you have a isMoving variable that is set depending on if your animation or whatever you do is in progress. Even though user scrolls multiple times with mousewheel in one "flick", the function fires only once.
$(document).ready(function(){
var up=false;
var down=false;
$('#foo').bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta /120 > 0 && up=false) {
up=true;
down=false;
$(this).text('scrolling up !');
}
elseif(e.originalEvent.wheelDelta /120 > 0 && down=false){
down=true;
up=false;
$(this).text('scrolling down !');
}
});
});
And here is a plug in you can use it
I have a page that I'm building and I would like to make it that when I scroll (up or down) the page scrolls to the next div (each div is 100% the height of the window). And gets "fixed" there until you scroll again. An example of what I'm trying to accomplish can be seen here:
http://testdays.hondamoto.ch/
You will notice that when you scroll down, it automatically moves you to the next "div".
What I've tried:
Using the jQuery .scroll event combined with:
function updatePosition() {
if(canScroll) {
var pageName;
canScroll = false;
var st = $(window).scrollTop();
if (st > lastScrollTop){
// downscroll code
if(pageNumber < 7) {
pageNumber++;
}
pageName = '#' + getPageToScrollTo().id;
$('body').animate({ scrollTop: $(pageName).offset().top }, 2000, function() {
canScroll = true;
});
} else {
// upscroll code
if(pageNumber > 0) {
pageNumber--;
}
pageName = '#' + getPageToScrollTo().id;
$('body').animate({ scrollTop: $(pageName).offset().top }, 2000, function() {
canScroll = true;
});
}
lastScrollTop = st;
}
}
But the scroll event was getting called when the page was scrolling (animating), AND when the user scrolled. I only need it to be called when the user scrolls.
Then I added:
var throttled = _.throttle(updatePosition, 3000);
$(document).scroll(throttled);
From the Underscore.js library - but it still did the same.
Finally, I browsed here a bit and found:
Call Scroll only when user scrolls, not when animate()
But I was unable to implement that solution. Is there anyone that knows of any libraries or methods to get this working?
EDIT:
Solution based on Basic's answer:
function nextPage() {
canScroll = false;
if(pageNumber < 7) {
pageNumber++;
}
pageName = getPageToScrollTo();
$('html, body').stop().animate({ scrollTop: $(pageName).offset().top }, 1000, function() {
canScroll = true;
});
}
function prevPage() {
canScroll = false;
if(pageNumber > 0) {
pageNumber--;
}
pageName = getPageToScrollTo();
$('html, body').stop().animate({ scrollTop: $(pageName).offset().top }, 1000, function() {
canScroll = true;
});
}
//--Bind mouseWheel
$(window).on(mousewheelevt, function(event) {
event.preventDefault();
if(canScroll){
if(mousewheelevt == "mousewheel") {
if (event.originalEvent.wheelDelta >= 0) {
prevPage();
} else {
nextPage();
}
} else if(mousewheelevt == "DOMMouseScroll") {
if (event.originalEvent.detail >= 0) {
nextPage();
} else {
prevPage();
}
}
}
});
Ok...
The relevant code for the Honda site can be found in http://testdays.hondamoto.ch/js/script_2.js. It seems to be doing some calculations to locate the top of the div then scroll to it. There are handlers for different types of scrolling.
Specifically, the movement is handled by function navigation(target)
the key bits is here...
$('html,body').stop().animate({
scrollTop: $(target).offset().top + newMargin
}, 1000,'easeInOutExpo',function(){
//Lots of "page"-specific stuff
}
});
There are handlers for the scroll types...
$('body').bind('touchstart', function(event) {
//if(currentNav!=3){
// jQuery clones events, but only with a limited number of properties for perf reasons. Need the original event to get 'touches'
var e = event.originalEvent;
scrollStartPos = e.touches[0].pageY;
//}
});
//--Bind mouseWheel
$('*').bind('mousewheel', function(event, delta) {
event.preventDefault();
//trace('class : '+$(this).attr('class') + ' id : '+$(this).attr('id'));
if(!busy && !lockScrollModel && !lockScrollMap){
if(delta<0){
nextPage();
}else{
prevPage();
}
}
});
You'll note that the navigate() function sets a busy flag which is unset when scrolling completes - which is how it suppresses all new scroll events during a scroll. Try changing the direction of scroll while the page is already scrolling and you'll notice user input is being ignored too.