Misplaced Scroll Bar When scrollTo Called - javascript

I am using the below function to scroll to a Div inside a Div.
It works but the car stays at last position so if the user scrolls it flashes to the original position. To clarify the scroll bar is actually at the top of the div but the user sees to bottom element but when user scrolls up he or she doesn't get the expected result of moving to the element right above the last they get bumped to the top.
jQuery.fn.scrollTo = function (elem, speed) {
$(this).animate({
scrollTop: $(this).scrollTop() - $(this).offset().top + $(elem).offset().top
}, speed == undefined ? 1000 : speed);
return this;
};
onclick="$('#usermessageDiv').scrollTo('.last_usermessage', 2000);"
$('.small-chat-box .content').slimScroll({
height: '234px',
railOpacity: 0.4
});
<div id="usermessageDiv" class="content" style="overflow: scroll; width: auto; height: 234px;">
The image below shows where the bar is vs the 2nd lower red arrow where the scroll bar should be in regards to the view shown.

SlimScroll has a scrollTo setting that you should use instead of your scrollTo function.
scrollTo - Jumps to the specified scroll value. Can be called on any
element with slimScroll already enabled. Example:
$(element).slimScroll({ scrollTo: '50px' });
You will need to use jQuery's position() method to get the scroll distance of the target element relative to the parent. If you need detailed help with that, please post some HTML for the usermessageDiv.

Related

How to check if the element is near the bottom of the screen?

How is the way to check if some the element is near the bottom of the screen let say 100px from the bottom? (not the bottom of page).
The thing is i wanted that when this element is clicked, an another element will shown up and will slide to top rather to down if is near the bottom of the screen?
You can identify when an element is under 100px from the bottom of the screen with the following condition (without the need to use jQuery):
if (window.innerHeight - element.getBoundingClientRect().bottom < 100){
// the desired place
}
I think what you want is a button that displays when the user is almost at the bottom of your screen and when the user clicks on it, it scrolls them back to the top of the screen.
You may want to use JavaScript to achieve this.
Using the jQuery library
<script type="text/javascript>
$(document).scroll(function(){
var x = $(this).scrollTop();
if (x > 250) //The 250 is the total height of div that the user scrolls to before the button displys for the user to click
{
$('.button').fadeIn();
} else {
$('.button').fadeOut();
}
$('.button').click(function() {
$('html, body').animate({
scrollTop: $('.topmost_div').offset().top}, 'slow'); //tell the page to scroll back to the div at the top of the page.
});
});
</script>
Hope this helps

JQuery scroll window to show div depending on its location

When I click my button, I append a new div. I would like that, if any part of the div is not visible to the window, scroll untill it shows.
So if it is upwards from the center of the window, scroll up JUST until you see it's top, and if it is downwards from the center, scroll down just until you see its bottom.
In my searchings I found https://api.jquery.com/scrollTop/ , but that doesn't seem to be what I'm describing
I only want to scroll enough to display it entirely on screen, not always on top
Check this working fiddle for the solution.
You can use scrollTop() to scroll to any div. First we need to find the direction of the scroll to correctly provide the value for scrollTop() function. This can be found using position().
$('#button4').click(function() {
// check if the div lies below the button
if ($('#div3').position().top - $('#button4').position().top > 0) {
// in this case we need to add shift
var shift = $(window).height() - $('#div3').height();
} else {
var shift = 0;
}
$(window).scrollTop($('#div3').offset().top - shift);
});
Alternatively if you wish to check the position of the div relative to the current viewport (or the center of the current window view) you can use getBoundingClientRect() like:
$('#button4').click(function() {
// check if the div lies below the viewport
if ($('#div3')[0].getBoundingClientRect().top > 0) {
// in this case we need to add shift
var shift = $(window).height() - $('#div3').height();
} else {
var shift = 0;
}
$(window).scrollTop($('#div3').offset().top - shift);
});
Here is the alternate fiddle.
So if you are using jQuery.
//scroll top of element
var $myNewElement = $(".new-element-class");
$('html, body').scrollTop($myNewElement.offset().top)
I think this should work. Make sure your div is appended before calling the scrollTop function.
If I understand correctly, this jsfiddle is what you are looking for.
I also added a simple animation so the document doesn't awkwardly jump around the viewport.
Features
If a new element is created, and part of that new element is below the current viewport, the document will be scrolled until the bottom of the viewport is shown. Vice versa if part of the new element is above the current viewport.
If the new element is completely visible within the current viewport, no scrolling will occur.
All scrolling effects are animated.
A configurable offset (Leave some padding instead of scrolling to the very edge of the new element)
How it works
When the button is clicked, a new div element is appended.
$('section').append('<div>');
Next, we figure out if this div is above the current viewport using the below function:
function isElementAboveViewport(element) {
return $(element).offset().top < $(window).scrollTop();
}
in an if statement:
if (isElementAboveViewport($('section > div:last-child'))) {
...
}
If the condition is truthy, we scroll! (offset is configurable - In the JS fiddle, I used 40 which is the height of the button covering the top 40px of the viewport)
$('html, body').animate({
scrollTop: $('section > div:last-child').offset().top - offset
}, 1000);
Now, we check if the new element is below the current viewport with a similar function:
function isElementBelowViewport(element) {
return $(element).offset().top + $(element).height() > $(window).scrollTop() + $(window).height();
}
If the element is too far down in the document, we scroll! (Again, offset is configurable)
$('html, body').animate({
scrollTop: $('section > div:last-child').offset().top + $('section > div:last-child').height() - $(window).height() + offset
}, 1000);
Please let me know if this is what you were looking for and/or if you have any questions about how it works.

How to use the same jQuery scrolling function for multiple elements

I have a scrolling function that reveals a 'scroll to top' element when user scrolls to 160 pixels, when clicked this element the page scrolls to the top of the page.
I want to use that function create more scroll buttons which will be revealed at different stages in the document and that scroll to different areas.
For example when the user scrolls to 400 pixels down the element "next" appears when clicking it page scrolls 300px down, they get to 900px from top a new scroll element appears which when clicked scrolls down to 1300px, and so on.
here is the jQuery code i have:
$(document).ready(function(){
$(window).scroll(function(){
if ($(this).scrollTop() > 160) {
$('.scrollToTop').fadeIn();
} else {
$('.scrollToTop').fadeOut();
}
});
$('.scrollToTop').click(function(){
$('html, body').animate({scrollTop : 0},800);
return false;
});
});
HTML:
<div class="scrollToTop-container">
<img src="img/icon_arrow_up.png" width="24" height="24" /> <br/>Scroll to top
</div>
i hope thats not too confusing.
Thanks
Maybe you can use a function like this I made reusing some parts of your code:
function scroll(id,show,limit,timeout){
$(window).scroll(function(){
if ($(this).scrollTop() > show) {
$(id).fadeIn();
} else {
$(id).fadeOut();
}
});
$(id).click(function(){
$('html, body').animate({scrollTop : limit},timeout);
return false;
});
}
And then use it like this:
scroll(".scrollToTop",160,0,800);
where first parameter is class or id you want to be affected, second is the position of the element at certain height (from top), third is limit (where you want to scroll up) and last one is the duration of the animate function.
EDIT: You may also like to stop on specific px, not only scroll to top, so I changed the function to set the scrollTop position at your desire.

Parallax scroll, animation WITH scroll instead of activate on scroll

I am diving into 'Parallax scroll' styled web pages, I can style all my main sections correctly with background image animations however when I break it down further into individual div animations I am getting stuck.
Example: Once the browser scroll hits 900px it activates a div to animate in from the left. It slides all the way into place. What I am trying to accomplish is that the animation is controlled by the user scroll completely (only animates on scroll). Hope this makes sense
Fiddle: http://jsfiddle.net/WW8xF/
HTML
<section id="one"></section>
<section id="two">
<div class="contentBox">I am a box</div>
</section>
jQuery
$(window).scroll(function(){
if($(window).scrollTop()<500) {
$('.contentBox').stop().animate({ left: -500 }, { duration: 500 });
} else {
$('.contentBox').stop().animate({ left: 100 }, { duration: 500 });
}
});
In this case you don't want to use animate, you want to control the position of your element yourself based on the scroll position of the window. Something like this:
http://jsfiddle.net/WW8xF/1/
$(window).scroll(function(){
var position = Math.min($(window).scrollTop()-700, 100)
$('.contentBox').css({ left: position });
});
You can adjust the logic of position here to affect when it moves, where it stops, etc.

Can someone explain why this code works-making div stick to top after scoll?

I love that this code works, but I cannot, for anything, wrap my head around WHY it's working?
Here is the jfidddle
Here is the code:
jQuery(document).ready(function($) {
clone = $('div').clone();
$('div').after(clone);
$('div:last').hide();
offset = $('div:first').offset();
var fromtop = offset.top;
$(document).scroll(function() {
doc = $(this);
dist = $(this).scrollTop();
if (dist >= fromtop) {
$('div:last').show();
$('div:first').css({
'position': 'fixed'
});
} else {
$('div:first').css({
'position': 'static'
});
$('div:last').hide();
}
});
});
I guess I am not understanding how scrolltop and offset are interacting or what they REALLY are, as in their true positions on the page. The code says if ScrollTop (the scrollbar position?) is higher than the value of the div's offsettop , then make the div sticky. But if ScrollTop is the position of the scrollbar, isn't it true that sometimes the scroll bar position could be lower than the div's position BEFORE the div is at the top of the page? What is it about being at the top of the page (offsettop of 0?)--and only at the top of the page, never before-- that makes offsettop a smaller value than scrolltop?
Really confused, and I don't want to just copy the code without understanding what it's really doing.
scroll Top is actually how many pixels 'up' the page has moved (or how many pixels you have moved down the page)
Basically all that happens is the .offset sees how far down the page (from the top of the page) the 'sticky' menu is
When you scroll to that point the bar becomes fixed (which is basically relative to the window instead of the document)
When you scroll back up it just switches back to being positioned in the document.
For clarity
.offset = 200px say - this is how far down the document the sticky menu is
.scrollTop - is 0 when the page loads
When you scroll down the page 201px
.scrollTop > .offSet -> so make the bar fixed (remember fixed is relative to the window - not the document)
If you scroll back up the process is reversed.
It's actually very simple. Let me try if I can make it a bit clear to you:
Whenever you want something (let's say some div) to get fixed on top as you scroll down, you need two things:
You need the current vertical position of your div. And you calculate that by using offset().top
You need to track how much user has scrolled. And you calculate that by using scrollTop()
So in your case, if the current position of your div is top: 100, then as soon as your scrollbar reaches the number 101, your div will get the class of .fixed
By default, the scrollbar vertical position is 0 when the page loads.

Categories