Infinite scroll based on mouse scroll - javascript

Want to implement infinite scroll based on mouse scrol when it reaches the specified container bottom. I came to this plugin after searching http://www.infinite-scroll.com/ which needs the following basic requirements:
// infinitescroll() is called on the element that surrounds
// the items you will be loading more of
$('#content').infinitescroll({
navSelector : "div.navigation",
// selector for the paged navigation (it will be hidden)
nextSelector : "div.navigation a:first",
// selector for the NEXT link (to page 2)
itemSelector : "#content div.post"
// selector for all items you'll retrieve
});
i.e next and previous selectors. Can we have infinite scroll based on mouse scroll instead of clicking next, prev links i.e when mouse reaches the specified container bottom load the content via ajax

Add a function to the scroll event and check if you scrolled down to the bottom.
you have to adjust numbers and tweak the code a bit according to your layout:
var $window = $(window);
$(document).ready(function () {
$(window).scroll(function () {
var scrollheight2;
scrollheight2 = $window.scrollTop();
if (($("#content").height() - scrollheight2) <= 100) {
//AJAX STUFF
}
});
});

Related

Jquery scroll function to apply whenever page is reloaded when scrolling had already taken place before the reload

I already know that I can use the jQuery scroll() method to apply a scrolled class to my navbar, which then allows me to do interesting things like change the background color of the navbar when the user scrolls down.
$(document).scroll(function () {
var $nav = $("nav.fixed-top");
$nav.toggleClass('scrolled', $(this).scrollTop() > $nav.height());
});
This method fails however, when the user has already scrolled (and thereby applied the scrolled class), and then reloads the page. Immediately on reloading, there is no scroll class. It makes for some ugly looking UI.
How can I change this code such that whenever the page loads, it checks to see if the page is not at the top, and if it isn't, still applies the scrolled class? This way if the user scrolls to the middle and reloads the page, the browser is able to apply the scrolled class and therefore the appropriate css?
Examples:
Image before scrolling
Image of UI when scrolled class is added
Image of UI when reloaded after scrolled class has applied
On ready event you can check if user has scrolled
$(document).ready(() => {
$nav.toggleClass('scrolled', 0 < $(window).scrollTop());
});
While your page is loading (and you're scrolling), there's a great chance jQuery hasn't loaded yet, therefore the scroll event will not be triggered in your code.
You can get the number of pixels that the user has scrolled (after the page is loaded) using $("html").scrollTop(). If this is 0, it means you're at the top of the page.
$(document).scroll(function () {
let $nav = $("nav.fixed-top");
$nav.toggleClass('scrolled', $(this).scrollTop() > $nav.height());
}).ready(function () {
let $nav = $("nav.fixed-top");
$nav.toggleClass('scrolled', $(this).scrollTop() > $nav.height());
});
The .ready() event will be triggered once the page loads.

Haphazard Scrolling on double click jquery

I am trying to get scrolling right on div tags by clicking on list of anchor tags using jquery.
enter code here
function scrollThere(targetElement, speed) {
// initiate an animation to a certain page element:
$('html, body , #side').stop().animate(
{ scrollTop: targetElement.offset().top }, // move window so target
element is at top of window
speed, // speed in milliseconds
'swing' // easing
); // end animate
} // end scrollThere function definition
//--- START NAV-ITEM CLICK EVENTS ---//
// when the user clicks a nav item:
$("#leftSidebar ul li a").click(function (e) {
e.preventDefault(); // don't jump like a typical html anchor
// find the index of the "#" character in the href string...
var startOfName = $(this).attr('href').indexOf("#"),
// ...then use it as the argument in the slice() method (add 1 so you
don't include the # character).
clickRef = $(this).attr('href').slice(startOfName + 1),
targetEl = $('a[name=' + clickRef + ']'); // select the element this
link is pointing to
// scroll there smoothly:
scrollThere(targetEl, 400);
});
The problem is that when I click on a link twice,it takes me to the top of the page and the scrolling messes up too.The scrolling for some reason dosent work properly as the size of div tags increase.Here is a fiddle https://jsfiddle.net/60tp46y3/18/ showing the problem.Ideally on clicking respective links on left the right section should scroll to the appropriate id.
Just adapted your code. It's working now.
https://jsfiddle.net/t0of2kzp/
The error was, that you didn't checked the current scroll position of the container, which contains all other elements.
// targetElement is the div surrounding the target a tag.
var postionOfTargetElement = targetElement.offset().top;
// That's the main container
var scrollPosition = targetElement.parent().scrollTop();
// Here we calculate the real top position with respecting the main containers scroll position.
var topTarget = postionOfTargetElement + scrollPosition;

Scrolling animation breaks links on page

I replaced the scrolling animation of my one page website with another scrolling animation which changes the URLs when you use the topbar (it was build in foundation)
While the URLs now change when I click an item in the topbar all the other links or clickable elements on my page make it scroll back to the top of the page.
For example when I try to click the next/prev buttons of my slider it scrolls back to the top of the page as if I clicked on Home.
Can someone see whats wrong with the code for the animation?
$(document).ready(function () {
$('a[href^="#"]').click(function () {
var target = $(this.hash),
hash = this.hash;
if (target.length == 0) {
target = $('a[name="' + this.hash.substr(1) + '"]');
}
if (target.length == 0) {
target = $('html');
}
$('html, body').animate({
scrollTop: target.offset().top
}, 500, function () {
location.hash = hash;
});
return false;
});
});
PS: When I scroll manually the URLs don't change when I go down to the next page. If anyone has a fix for this I'll be happy to here from you! (I tried using history.js but that only seems to work if you have a server, which I don't)
//* EDIT *//
I just found out it's not all links that make it scroll to the top of the page, just the buttons of my orbit slider and the menu button when the topbar is collapsed
//EDIT 2//
The URL now changes when I scroll to the next page!
The only problem I am seeing right now is that the buttons of my orbit slider and the menu button of the collapsed topbar act the same as my home button (makes the page scroll all the way back to the top) for some reason.
So the last thing I need to do is get the buttons working again. Making the menu button expand the topbar and making the next and prev buttons of my slider work as normal
If you only want to change the hash depending on the scrollPosition you are half way there.
You'll need to bind some logic to the scroll event. Here is a fork of your Fiddle where the hash is changed on scroll.
When the user scrolls the page we iterate through all .page elements and compare their offset().top against $( document ).scrollTop().
We set the new hash to be the id of the last .page element that has a lower offset().top than $( document ).scrollTop() is.
(I also debounced the function so it doesn't fire constantly when scrolling - you could of course remove that part)
You should however consider that by changing the hash you will jump to the equivalent element. Here is a guide on how to suppress that behaviour.
EDIT:
Here is an updated Fiddle where I implemented the solution from above for suppressing forced scroll on hash change.

How to enable normal scroll behavior, at certain DIV element

I'm having a bit of trouble getting a one-page scroll to behave the way I want it to. I would like the first to be full page and when they scroll down, it will full page scroll to the next element. But when they reach the 2nd section element - it will revert to regular scrolling behavior. This is because the rest of the page is not full page or one page.
I basically want the intro to be a full page, and then do a full page scroll into the next section where they can freely scroll down normally. When they scroll back up to the first section it should full page scroll again to the intro.
I'm using the below code. This is working for the full page transition into section 2, but I can't figure out how to revert to normal scrolling behavior after they reach section 2.
$('section').height($(window).height());
/*set the class 'active' to the first element
this will serve as our indicator*/
$('section').first().addClass('active');
/* handle the mousewheel event together with
DOMMouseScroll to work on cross browser */
$(document).on('mousewheel DOMMouseScroll', function (e) {
e.preventDefault();//prevent the default mousewheel scrolling
var active = $('section.active');
//get the delta to determine the mousewheel scrol UP and DOWN
var delta = e.originalEvent.detail < 0 || e.originalEvent.wheelDelta > 0 ? 1 : -1;
//if the delta value is negative, the user is scrolling down
if (delta < 0) {
//mousewheel down handler
next = active.next();
//check if the next section exist and animate the anchoring
if (next.length) {
/*setTimeout is here to prevent the scrolling animation
to jump to the topmost or bottom when
the user scrolled very fast.*/
var timer = setTimeout(function () {
/* animate the scrollTop by passing
the elements offset top value */
$('body, html').animate({
scrollTop: next.offset().top
}, 'slow');
// move the indicator 'active' class
next.addClass('active')
.siblings().removeClass('active');
clearTimeout(timer);
}, 800);
}
} else {
//mousewheel up handler
/*similar logic to the mousewheel down handler
except that we are animate the anchoring
to the previous sibling element*/
prev = active.prev();
if (prev.length) {
var timer = setTimeout(function () {
$('body, html').animate({
scrollTop: prev.offset().top
}, 'slow');
prev.addClass('active')
.siblings().removeClass('active');
clearTimeout(timer);
}, 800);
}
}
});
To hide scrollbars of the browser (and thus to have the look of full page) apply overflow:hidden css-property to body like
$(document.body).css('overflow', 'hidden');
When you scrolled down via javascript to a section where the user should be able to scroll with standard scrolls just let scrollbar-handling be done automatically again by
$(document.body).css('overflow', 'auto');
So apply the first javascript-snippet whenever you scrolled via javascript to a fullpage view apply the latter everytime you scrolled to a normal scrollable section again.

Jump to content inside of a scrollable div

I got the following HTML:
<div style="height:200px;overflow-y:scroll;">
<table>.....</table>
</div>
With this setup I'm somewhat mimicking the expanded <select> control with #size attribute defined. So, that a user could select a row in the table. Is there a way, to make the table "jump up", so that the selected row appears to be at the top of the div and the vertical scrollbar scrolled to its position. I don't need the actual scrolling effect. The table should change it's position right away on row click.
This might work:
$("#scrollableDiv").animate({
scrollTop: 200 // scrolls to the bottom
}, 1000);
I suggest using scrollTop (or even animate it if you want).
$('div')[0].scrollTop = 200 //would set the scrollable div to 200px down.
http://jsfiddle.net/8mepH/
Here is an modified extract of the code used in:
http://www.balupton.com/sandbox/jquery-scrollto/demo/
To do what you want:
// Fetch the scrollable div
$container = $('#scrollable');
// Fetch the target div
$target = $('#target');
// Prepare the Inline Element of the Container
var $inline = $('<span/>').css({
'position': 'absolute',
'top': '0px',
'left': '0px'
});
var position = $container.css('position');
// Insert the Inline Element of the Container
$container.css('position','relative');
$inline.appendTo($container);
// Determine the Offsets
var startOffset = $inline.offset().top,
targetOffset = $target.offset().top,
offsetDifference = targetOffset - startOffset;
// Perform the jump
$container.css('scrollTop',offsetDifference+'px')
We add a inline here to ensure we get the correct start position within the scrollable area. We use a offset difference so if you want to do animations it animations from the start position, rather than jumping somewhere else.

Categories

Resources