Subtract from an integer using jquery - javascript

I want to scroll to a div each time user presses j key. Here is the code for it.
$(function() {
function scroll(direction) {
var scroll, i,
positions = [],
here = $(window).scrollTop(),
collection = $('.message_box');
collection.each(function() {
positions.push(parseInt($(this).offset()['top'],0));
});
for(i = 0; i < positions.length; i++) {
if (direction == 'next' && positions[i] > here) { scroll = collection.get(i); break; }
if (direction == 'prev' && i > 0 && positions[i] >= here) { scroll = collection.get(i); break; }
}
if (scroll) {
$('html, body').animate({"scrollTop": $(scroll).offset().top-50});
$(scroll).css('color', 'blue');
$(scroll).mouseleave(function() {
$(this).css('color', 'black');
});
}
return false;
}
$("#next,#prev").click(function() {
return scroll($(this).attr('id'));
});
$('body').keyup(function(event) {
if (event.which == 74) {
return scroll('next');
}
});
$('body').keyup(function(event) {
if (event.which == 75) {
return scroll('prev');
}
});
});
I need to subtract 50 from the offest of the div to scroll to which is this.
$('html, body').animate({"scrollTop": $(scroll).offset().top-50});
It will scroll the first time but not the rest of the times. I always get the integer 218 which is the offset of the first div to scroll to.
DEMO - http://jsfiddle.net/XP5sP/6/
Can someone help me ?

The problem is that you're always moving the scrollTop value to 50 pixels before the first matched element, so it's always identifying that element as the one you need to scroll to in your if statement because its position is greater than the current scrollTop value.
Modify the relevant section of your code to this:
if (direction == 'next' && positions[i] > here + 50) {
scroll = collection.get(i);
break;
}
That way it accounts for the window being scrolled to 50 pixels above the current element.

$(scroll).offset().top-50 is prefectly valid, as .top will return an integer value. Therefore the issue is not with this portion of your code.
I suspect the issue is to do with the scroll variable you have within the scroll function. I always keep away from naming my variables the same as my function names when within the same scope.

Try putting some space between your minus symbol so it does not get mistaken for a dash.
$('html, body').animate({"scrollTop": $(scroll).offset().top - 50});
or save your mathematics in a variable first
var scrollMinusFifty = $(scroll).offset().top - 50;
$('html, body').animate({"scrollTop":scrollMinusFifty});

Related

Javascript Element.ClassName always returning true on mousewheel change

I have a scroll wheel function that changes the class of a div as you scroll down or up.
It is actually functioning really well in all modern browsers, the thing is, it is trying to change the class everytime it is executing, even though I have a validation that should stop this from happening.
The function asks that if the div already has that class active then it should not change, but if you look at the console it is trying to do it every time despite that validation.
I don't know why the className method always returns true.
I used jquery's hasClass function and had the same behavior.
Thank you so much for your help.
JAVASCRIPT CODE:
var sections = ['one', 'two', 'three', 'four', 'five'];
function changeSection(section) {
for (var x = 0; x < sections.length; x++) {
$('#bg-main').removeClass('bg-' + sections[x]);
if (sections[x] === section) {
if (document.getElementById('bg-main').className != ('bg-' + section)) {
$('#bg-main').addClass('bg-' + section);
console.log("Active: " + section);
} else {
console.log("Inactive: " + sections[x]);
}
}
}
}
var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel"
if (document.attachEvent)
document.attachEvent("on" + mousewheelevt, displaywheel)
else if (document.addEventListener)
document.addEventListener(mousewheelevt, displaywheel, false)
var position = 0;
function displaywheel(e) {
var evt = window.event || e
var delta = evt.detail ? evt.detail : evt.wheelDelta
if (delta < 0) {
position = (mousewheelevt == 'DOMMouseScroll') ? position - 1 : position + 1;
} else {
position = (mousewheelevt == 'DOMMouseScroll') ? position + 1 : position - 1;
}
if (position < 0) position = 0;
if (position > 100) position = 100;
// Change sections on Scroll
if (position >= 0 && position <= 19) {
changeSection('one');
} else if (position >= 20 && position <= 39) {
changeSection('two');
} else if (position >= 40 && position <= 59) {
changeSection('three');
}
if (position >= 60 && position <= 79) {
changeSection('four');
} else if (position >= 80 && position <= 100) {
changeSection('five');
}
}
CSS CODE:
#bg-main {
width: 100%;
height: 300px;
}
.bg-one {
background-color: blue;
}
.bg-two {
background-color: red;
}
.bg-three {
background-color: green;
}
.bg-four {
background-color: yellow;
}
.bg-five {
background-color: purple;
}
HTML CODE:
<div id="bg-main" class="bg-one">SCROLL TO SEE THE CHANGE OF BACKGROUND</div>
Working fidddle:
https://jsfiddle.net/9vpuj582/
You are removing the class before you check to see if the element has the class that you passed into your function (so your if statement will never evaluate as false).
The placement of the following line of code in your changeSection function is your issue:
$('#bg-main').removeClass('bg-'+sections[x]);
You could simplify your current function quite a bit. First check if the element already has the class you want. Then, if not, remove all classes from the element (rather than looping through them and checking each one) and then add the new class. For example:
const bg = $('#bg-main');
function changeSection(section) {
if (!bg.hasClass('bg-' + section)) {
bg.removeClass();
bg.addClass('bg-' + section);
}
}

classList and scroll event

I have some simple script to adding classes to my navbar relied on pageYOffset:
var navContainer = document.querySelector('.nav-container');
var firstTitle = document.querySelector('.first-title')
document.addEventListener('scroll',function(){
if(window.pageYOffset < 75){
navContainer.classList.remove('nav-action','yellow');
}else if(window.pageYOffset > 75){
navContainer.classList.add('nav-action')
}else if(window.pageYOffset<firstTitle.offsetTop){
navContainer.classList.remove('yellow');
}
else if(window.pageYOffset > firstTitle.offsetTop){
navContainer.classList.add('yellow');
};
});
my trouble is this that last condition is fulfilled when window.pageYOffset is bigger than firstTitle.offsetTop, writing this line between brackets in the console returns true, but nothing happens when I'm trying this all code.
Unless window.pageYOffset === 75, none of these lines will actually be executed. The previous conditions already catch all the cases.
I would suggest treating nav-action and yellow separately:
var navContainer = document.querySelector('.nav-container');
var firstTitle = document.querySelector('.first-title')
document.addEventListener('scroll', function() {
if (window.pageYOffset < 75) {
navContainer.classList.remove('nav-action');
} else {
navContainer.classList.add('nav-action')
}
if (window.pageYOffset < firstTitle.offsetTop) {
navContainer.classList.remove('yellow');
} else {
navContainer.classList.add('yellow');
}
});

How to change this script to autoscroll?

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.

Auto-Scroll to next anchor at Mouse-wheel

I have 5 anchors on my html page. Is there any way that the page scrolls automatically to the next anchor (#) by a single Mouse-wheel scroll? Is there a way that it happens regardless of the anchor's name? just to the next anchor.
This works in Chrome, IE, Firefox, Opera, and Safari:
(function() {
var delay = false;
$(document).on('mousewheel DOMMouseScroll', function(event) {
event.preventDefault();
if(delay) return;
delay = true;
setTimeout(function(){delay = false},200)
var wd = event.originalEvent.wheelDelta || -event.originalEvent.detail;
var a= document.getElementsByTagName('a');
if(wd < 0) {
for(var i = 0 ; i < a.length ; i++) {
var t = a[i].getClientRects()[0].top;
if(t >= 40) break;
}
}
else {
for(var i = a.length-1 ; i >= 0 ; i--) {
var t = a[i].getClientRects()[0].top;
if(t < -20) break;
}
}
if(i >= 0 && i < a.length) {
$('html,body').animate({
scrollTop: a[i].offsetTop
});
}
});
})();
Fiddle at http://jsfiddle.net/t6LLybx8/728/
How it works
To monitor the mouse wheel in most browsers, use $(document).on('mousewheel'). Firefox is the oddball, and it requires $(document).on('DOMMouseScroll').
To get the direction of the mouse wheel (up or down), use event.originalEvent.wheelDelta. Again, Firefox is the oddball, and you have to use -event.originalEvent.detail.
If the direction is a negative number, you're scrolling down the page. In that case, loop through each tag beginning with the first, until its first getClientRects() top is >= 40. (I used 40, in case the browser adds a default margin at the top of the viewport.)
If the direction is a positive number, you're scrolling up the page. In that case, loop through each tag beginning with the last, until its first getClientRects() top is < -20. (I used -20 to ensure we move up the page.)
The delay variable prevents the mouse wheel from scrolling too quickly. The entire function is wrapped in a closure, so delay remains a private variable.
let's say you have array of IDs.then you can do something like...
var ancherList = ["id1","id2","id3"];
var currentPosition = null;
var mousewheelevent = 'onwheel' in document ? 'wheel' : 'onmousewheel' in document ? 'mousewheel' : 'DOMMouseScroll';
$(document).on(mousewheelevent,function(e){
var scrollToAncher function (id,speed){
spd = speed ? "slow" //deafult value for the animation speed
var ancherTag = $("a[name='"+ id +"']");
$('html,body').animate({scrollTop: ancherTag.offset().top},spd);
}
e.preventDefault();
var delta = e.originalEvent.deltaY ? -(e.originalEvent.deltaY) : e.originalEvent.wheelDelta ? e.originalEvent.wheelDelta : -(e.originalEvent.detail);
if (delta > 0){
console.log("up")
//check your current position and target id
switch(currentPosition){
case null :
case ancherList[0] :
scrollToAncher(ancherList[1]);
currentPosition = ancherList[1];
break;
case ancherList[1] :
currentPosition = ancherList[2];
scrollToAncher(ancherList[2]);
break;
case ancherList[2] :
currentPosition = ancherList[0];
scrollToAncher(ancherList[0]);
break;
}
} else {
console.log("down")
//do the same for mouse wheel down
}
});
code ain't tested.sorry if there was syntax error

Treating each div as a "page" when scrolling

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.

Categories