I need to implement a scroll function in my site.
When I will scroll down, document will be scrolled until a fixed position, which I want.
For example:
$(“.scroll-block”).scrollTop(250);
I realized this function. Pseudo-code:
when (scrollTop > 0)
do (scrollTop(250))
But then scroll is fixed. And any scroll-actions doesn’t work.
But I have three block. And I want to keep the possibility to scroll to all three blocks.
How can I do that?
P.S.: sorry for my terrible English. It’s my first post on this platform for communication.
P.S.S.: and first topic on English language.
Register a scroll callback like so:
jQuery(window).scroll(scrollCallback);
In the callback you can get the scroll position and do whatever you want at specific heights.
function scrollCallback(){
//gets the current windows scroll top value
var scrollPos = jQuery(window).scrollTop();
//get the position of the top of the elements you want to trigger actions on.
var first = jQuery('the-element-you-want-to-select1').position().top;
var second = jQuery('the-element-you-want-to-select2').position().top;
if(scrollPos > first){
//do something for first height
}else if(scrollPos > second){
//do something for second height
}
..
..
}
Related
Hi Guys,
I'm not so good with jQuery and javascript.
I will make a script that take the position of my div and when it's on the top of the page it make something.
Example:
I have a menu. When i scroll the page and my div arrive at the top (or better at 100/200px from top), something in my menu changes...
I hope somebody can help me.
Thanks.
You should use the jQuery offset() scrollTop() and scroll() methods to achieve this.
http://api.jquery.com/offset/
https://api.jquery.com/scrollTop/
https://api.jquery.com/scroll/
Offset returns the pixel value of the elements from the top of the page. Run this on scroll, and you can detect when the element is 100px, or 200px from the top.
Here is an example of running offset() and scrollTop() on window.scroll(), and adding/removing classes when the element has reached the top of this page. In this example, I am fixing the $mainMenuBar to the top of the page when the user scrolls past it, and un-fixing it when the user scroll back up past it.
// declare vars
var $window = $(window),
$mainMenuBar = $('.anchor-tabs'),
$mainMenuBarAnchor = $('.anchor-tabs-anchor');
// run on every pixel scroll
$window.scroll(function() {
var window_top = $window.scrollTop();
var div_top = $mainMenuBarAnchor.offset().top;
if (window_top > div_top) {
// Make the div sticky.
$mainMenuBar.addClass('fixed-top');
$mainMenuBarAnchor.height($mainMenuBar.height());
}
else {
// Unstick the div
$mainMenuBar.removeClass('fixed-top');
$mainMenuBarAnchor.height(0);
}
});
Hope this helps.
You can compare the offset of your div element to how far down the page the user has scrolled.
The $(window).scrollTop() function get you how far the user has scrolled down, i.e :
$(window).scroll(function() {
var yourDiv = $("#theIdOfYourDiv");
var window_offset = yourDiv.offset().top - $(window).scrollTop();
if ( window_offset < 100 )
{
// do what you want
}
});
Is it possible via Javascript to store how far a user has scrolled while on page (pixel-wise), regardless of where they are at any time?
For example, I'd like to track how far someone scrolled before going back up to do a specific action at the top of the page.
Thanks!
Simply save the scroll position if it's the lowest one, every time a scroll happens.
var maxScroll = 0;
$(window).scroll(function () {
var scroll = $(document).scrollTop();
if (scroll > maxScroll) maxScroll = scroll;
});
// maxScroll is at any time the lowest point of vertical scrolling on the page.
You might want to debounce the handler for better performance.
I have a button back-to-top that is affixed to the left side of the screen - it uses scrollTop to slide-scroll to the top of the page when it's clicked. When the page the loads, the button is visible and does not cover anything that is readable etc.
When a user scrolls down the page, the button goes over certain DIVs that have text content. When the button goes into such a DIV I want it to hide using .hide(). Can't get it to work, here's what I have:
var p = $('a.back-to-top');
var position = p.position();
if(position == $('#about-me')){
$('a.back-to-top').hide();
}
Is if(position == $('#about-me')) the correct way to check if the button's position is in the #about-me DIV? Or, should I create a variable similar to position for the DIV?
EDIT: A messy but simple fiddle
You will need to do this check inside of a callback .. probably $(window).scroll so that it is checked each time the window scrolls; otherwise, it is only checked when the page loads.
I don't think you want to use position either as that is position relative to parent. Instead, you probably want .offset. This returns an object with top and left members. An == comparison does not make sense, especially to a jQuery object. You want to use:
$(window).on('scroll', function () {
var offset = $("a.back-to-top").offset().top;
var within = $("#about-me").offset().top;
if (offset >= within && offset <= within + $("#about-me").height()) {
$("a.back-to-top").hide();
}
else {
$("a.back-to-top").show();
}
});
The offset of .back-to-top changes with scrolling if it has a fixed position, but the offset of the static block does not change, so you can do this comparison.
See it in action: http://jsfiddle.net/QnhgF/
http://api.jquery.com/position/ - position() method returns a position object which has .left and .top properties. So basically, you can't compare position to some object returned by a selector. Instead, you should compare the "top" property values of both elements.
For example you have:
var p = $('a.back-to-top');
var position = p.position();
Also get this:
var aboutMePosition = $('#about-me').position();
And then you can compare:
aboutMePosition.top and position.top whichever way you need.
I'm trying to create my own custom parallax plugin so that I am able to choose the direction the items transition off the screen and I'm just stuck at making sure that no matter how a user scrolls and no matter of the size of the window that the object disappears at the correct point.
Currently I have:
var lastScrollTop = 0;
var logoStartPos = $('.bg-logo').position().left;
$(function(){
$(window).scroll(function(){
var st = $(this).scrollTop();
if (st > lastScrollTop){
if($('.bg-logo').is(':in-viewport'))
$('.bg-logo').css({'left':($('.bg-logo').position().left+10) + "px"});
} else {
if($('.bg-logo').is(':in-viewport') && logoStartPos < $('.bg-logo').position().left)
$('.bg-logo').css({'left':($('.bg-logo').position().left-10) + "px"});
}
lastScrollTop = st;
});
});
As you can guess this only moves the item right until it goes off screen. This way has varied results because if I use the scroll wheel it take longer to disappear to if I use the scroll bar. I also have another problem in that if I use a mixture or have a different view port I get an different result all together.
Any tips or pointers to achieve the result I'm after?
An working example of my code is at http://motoring.egl.me.uk
Thanks Matt
A bit dated, but FYI...
In your jQuery initialize or ready event, you need to initialize each section, article, item or whatever it is (item.each) to instantiate a scroll function, so that each one has it's own scroll function.
this.each(function(index) {
Then in scroll function, only handle the event, if it is the 'current' section. You will need some way to determine which item is the 'current' one. Often this is done by saving each item's window size into a global array, and then using that compare to the current location.
Something like: (The way you designed your code will likely be very different)
// If this section is in view
if ( ($window.scrollTop() + $window.height()) > (topOffset) &&
( (topOffset + $self.height()) > $window.scrollTop() ) )
In this way, once one item goes off the screen, the next item should become 'current' and continue the scrolling.
This is a followup question for this:
Scrollpane on the bottom, css is hacky, javascript is hard
I ended up doing the scrolling in the same way explained in the accepted answer.
Now there is a request that one item is selected somehow (eg. as an url parameter or by some javascript calls) I should scroll the pane to the item with the corresponding ID in the scrollpane. Like a link to an anchor () would work!
I want to make a javascript call like this
function scrollTo(id) {
$('#middle').magicallyScrollThatItemWouldBeVisible(itemid);
}
But this is not in jQuery (or at least I don't know of it). So is there a way to make it?
I'll post a simple jsFiddle here:
http://jsfiddle.net/ruisoftware/U6QdQ/4/
Help me write that scrollTo function!
A .animate would be fine too.
UPDATE: If it was not clear I would like it to only align to the left or right side of the panel, it it was overflowed on that side (so the minimum possible amount of scrolling happens)
It's not jQuery, just JavaScript, and I've actually never used it all, so I'm not sure how you would have to mess with it to get it to work in this situation, but there is a scrollIntoView function:
yourElement.scrollIntoView();
Since the elements have a fixed width, you can count the number of elements by using .index() + 1, and animate to this value (after subtracting the container's width).
If you want the element to be centered, use - Math.round(middle.width()/100)*50.
Fiddle: http://jsfiddle.net/U6QdQ/17/
//This code should be run on load / DOMReady
(function($){ //Run on load / DOMReady
$.fn.magicScrollTo = function(){
var middle = $("#middle");
var currentScrollLeft = middle.scrollLeft();
var width = middle.width();
var newScrollLeft = this.offset().left + currentScrollLeft - middle.offset().left;
if(newScrollLeft >= currentScrollLeft && newScrollLeft <= currentScrollLeft + width - this.outerWidth()) return;
if(newScrollLeft > currentScrollLeft){ //If the element is at the right side
newScrollLeft = newScrollLeft - width + this.outerWidth();
}
middle.animate({
scrollLeft: newScrollLeft,
}, 'fast')
}
})(jQuery);
Usage:
//Select the 4rd element, and scroll to it (eq is zero-based):
$('.item').eq(3).magicScrollTo();
Something along these lines would be a good start:
http://jsfiddle.net/vHjJ4/
This will bring the target into the centre of the carousel. I think you will have to add in some extra checks to make sure that it didn't scroll to far, for example if you targeted the first or last element...unless this is built into the scroll function (it might be).
I'm not sure I understand your question exactly, but it sounds like you're asking how to scroll horizontally to the selected item in the bottom pane. If so, try something like this:
//get the position of the element relative to the parent ("middle")
var pos = $("#itemid").position();
if (pos){
$("#middle").scrollLeft(pos.left);
}
From here, you can use the width of middle to center the item if needed.