I have this site:
link
In the right sidebar, you'll notice that the last element runs with scrolling.
The problem is that does not stop ... go to the bottom of all.
I tried this function to accomplish the task
CODE JS:
var aux=0;
$("#text-3").addClass("follow-scroll");
var _footerH=$("#footer-container").outerHeight();
var _docH=$(document).height();
var _scrollP= $(window).scrollTop();
console.log("pozitie scroll",_scrollP);
console.log("inaltime footer",_footerH);
console.log("inaltime document HTML",_docH);
var element = $('.follow-scroll'),
originalY = element.offset().top;
var topMargin = 20;
element.css('position', 'relative');
$(window).on('scroll', function(event) {
var scrollTop = $(window).scrollTop();
console.log(scrollTop);
console.log("originalY:",originalY);
console.log("Scrolltop:",scrollTop);
console.log("topMargin:",topMargin);
var y = scrollTop - originalY + topMargin;
if(scrollTop < originalY) {
console.log("nu s-a declansat evenimentul");
}else {
//aici trebe adaugat top la div
aux=scrollTop - originalY + topMargin
$( '.follow-scroll' ).css( 'top', aux );
if(scrollTop>6000)
{
var _div = $( ".follow-scroll" );
var position = _div.position();
var top2=aux;
//aici trebuie sa primeasca ultimul top
$( '.follow-scroll' ).css( 'top', aux );
}
}
// top=aux;
// console.log("top_nou:",aux);
});
Can you help me solve this problem?
How can I stop this element at some point?
Thanks in advance!
Try changing your code to this
var aux = 0;
$("#text-3").addClass("follow-scroll");
var _footerH = $("#footer-container").outerHeight();
var _docH = $(document).height();
var _scrollP = $(window).scrollTop();
console.log("pozitie scroll", _scrollP);
console.log("inaltime footer", _footerH);
console.log("inaltime document HTML", _docH);
var element = $('.follow-scroll'),
originalY = element.offset().top;
var topMargin = 20;
element.css('position', 'relative');
$(window).on('scroll', function (event) {
var scrollTop = $(window).scrollTop();
console.log(scrollTop);
console.log("originalY:", originalY);
console.log("Scrolltop:", scrollTop);
console.log("topMargin:", topMargin);
var y = scrollTop - originalY + topMargin;
if (scrollTop < originalY) {
console.log("nu s-a declansat evenimentul");
} else {
//aici trebe adaugat top la div
aux = scrollTop - originalY + topMargin
if (scrollTop > 6000) {
var _div = $(".follow-scroll");
var position = _div.position();
var top2 = aux;
//aici trebuie sa primeasca ultimul top
}else{
$('.follow-scroll').css('top', aux);
}
}
});
You will notice the that you should only set $('.follow-scroll').css('top', aux); if scrollTop <= 6000 otherwise leave it where it is
Related
everyone! Searching the internet for solutions related to stick a widget in the sidebar I've found one that I liked. But, the only problem is that it doesn't "break" before the footer. I've already tried a lot of solutions, but without sucess until now. If someone can help me, I thank!
This is the original script:
<script type='text/javascript'>
/*<![CDATA[*/
// Sticky Plugin
// =============
// Author: Anthony Garand
// Improvements by German M. Bravo (Kronuz) and Ruud Kamphuis (ruudk)
// Created: 2/14/2011
// Date: 9/12/2011
// Website: http://labs.anthonygarand.com/sticky
// Description: Makes an element on the page stick on the screen as you scroll
// For Blogger by : http://www.makingdifferent.com
(function($) {
var defaults = {
topSpacing: 0,
bottomSpacing: 0,
className: 'is-sticky',
center: false
},
$window = $(window),
$document = $(document),
sticked = [],
windowHeight = $window.height(),
scroller = function() {
var scrollTop = $window.scrollTop(),
documentHeight = $document.height(),
dwh = documentHeight - windowHeight,
extra = (scrollTop > dwh) ? dwh - scrollTop : 0;
for (var i = 0; i < sticked.length; i++) {
var s = sticked[i],
elementTop = s.stickyWrapper.offset().top,
etse = elementTop - s.topSpacing - extra;
if (scrollTop <= etse) {
if (s.currentTop !== null) {
s.stickyElement.css('position', '').css('top', '').removeClass(s.className);
s.currentTop = null;
}
}
else {
var newTop = documentHeight - s.elementHeight - s.topSpacing - s.bottomSpacing - scrollTop - extra;
if (newTop < 0) {
newTop = newTop + s.topSpacing;
} else {
newTop = s.topSpacing;
}
if (s.currentTop != newTop) {
s.stickyElement.css('position', 'fixed').css('top', newTop).addClass(s.className);
s.currentTop = newTop;
}
}
}
},
resizer = function() {
windowHeight = $window.height();
};
// should be more efficient than using $window.scroll(scroller) and $window.resize(resizer):
if (window.addEventListener) {
window.addEventListener('scroll', scroller, false);
window.addEventListener('resize', resizer, false);
} else if (window.attachEvent) {
window.attachEvent('onscroll', scroller);
window.attachEvent('onresize', resizer);
}
$.fn.sticky = function(options) {
var o = $.extend(defaults, options);
return this.each(function() {
var stickyElement = $(this);
if (o.center)
var centerElement = "margin-left:auto;margin-right:auto;";
stickyId = stickyElement.attr('id');
stickyElement
.wrapAll('<div id="' + stickyId + 'StickyWrapper" style="' + centerElement + '"></div>')
.css('width', stickyElement.width());
var elementHeight = stickyElement.outerHeight(),
stickyWrapper = stickyElement.parent();
stickyWrapper
.css('width', stickyElement.outerWidth())
.css('height', elementHeight)
.css('clear', stickyElement.css('clear'));
sticked.push({
topSpacing: o.topSpacing,
bottomSpacing: o.bottomSpacing,
stickyElement: stickyElement,
currentTop: null,
stickyWrapper: stickyWrapper,
elementHeight: elementHeight,
className: o.className
});
});
};
})(jQuery);
/*]]>*/
</script>
I want my social sidebar make scroll only within the gray div. I have already put the sidebar within the gray div does not exceed the footer or the content above. My difficulty is to sidebar scroll accompanying the scroll without going gray div.
http://test.eae.pt/beautyacademy/angebot/
JS:
beautyAcademy.sharer = {
element: void 0,
elementToScroll: void 0,
init:function() {
this.element = $('.js-sharer-ref');
console.log(this.element.length);
if(this.element.length != 1) {
return;
}
this.build();
},
build: function() {
this.binds();
},
binds: function() {
var _this = this;
// Element that's gonna scroll
this.$elementToScroll = $('.fixed-social');
// Element that's gonna scroll height
this.elementToScrollHeight = this.$elementToScroll.outerHeight();
// Element where scroll is gonna happen Height
this.elementHeight = this.element.outerHeight();
// Element where scroll is gonna happen distance to top
this.elementOffsetTop = this.element.offset().top;
// Scroll that was done on the page
this.windowScrollTop = $(window).scrollTop();
this.elementOffsetBottom = this.elementOffsetTop + this.elementHeight - this.elementToScrollHeight;
this.$elementToScroll.css('top', (_this.elementOffsetTop+80) + "px");
$(window).on('scroll', function() {
if(this.windowScrollTop + this.elementToScrollHeight < this.elementHeight )
this.$elementToScroll.css('margin-top', this.windowScrollTop );
});
}
};
You need to try like below :
$(function(){
if ($('#container').length) {
var el = $('#container');
var stickyTop = $('#container').offset().top; // returns number
var stickyHeight = $('#container').height();
$(window).scroll(function(){ // scroll event
var limit = $('#footer').offset().top - stickyHeight - 20;
var windowTop = $(window).scrollTop(); // returns number
if (stickyTop < windowTop){
el.css({ position: 'fixed', top: 0 });
}
else {
el.css('position','static');
}
if (limit < windowTop) {
var diff = limit - windowTop;
el.css({top: diff});
}
});
}
});
DEMO
I'm trying to get this div to stop at the bottom but for some reason once it reaches the bottom it starts jumping around.
Any ideas? It seems like even when bottom_offset < 181 it still keeps changing the css top property.
<script>
jQuery(document).ready(function() {
var el = jQuery('#contactBox');
top_offset = jQuery('#contactBox').offset().top - 60;
var box_height = el.height();
jQuery(window).scroll(function() {
var scroll_top = jQuery(window).scrollTop();
var bottom_offset = jQuery(document).height() - scroll_top - box_height;
var new_top_offset = jQuery(document).height() - box_height - 100;
if ((scroll_top > top_offset) && (bottom_offset > 180)) {
el.css('top', scroll_top - top_offset);
}
else if ((scroll_top > top_offset) && (bottom_offset < 181)) {
el.css('top', new_top_offset);
}
else {
el.css('top', '');
}
});
});
</script>
Not sure how the html and css is setup so I'm taking a guess.
If the div has a fixed position, you can remove the following code and it should stop at the bottom.
The new_top_offset made the div jump down when i scrolled near the bottom.
else if ((scroll_top > top_offset) && (bottom_offset < 181)) {
el.css('top', new_top_offset);
}
else {
el.css('top', '');
Well I went ahead and changed it so that it worked a bit differently. It would just calculate body height minus footer height and also do scroll top + height of the scrolling div, and then it only changes css if total_height < body_height.
Here's the code if anyone needs it in the future.
jQuery(document).ready(function() {
var el = jQuery('#contactBox');
top_offset = jQuery('#contactBox').offset().top - 60;
var box_height = el.height();
jQuery(window).scroll(function() {
var scroll_top = jQuery(window).scrollTop();
var total_height = scroll_top + box_height;
var body_height = jQuery('body').outerHeight() - 150;
if ((scroll_top > top_offset) && (total_height < body_height)) {
el.css('top', scroll_top - top_offset);
}
});
});
Update
I made a repo on GitHub:
https://github.com/yckart/Veil.js
Big thanks to Sargo Darya and Edward J Payton.
I've to create a header which slides up if you scroll down and vice versa. The problem is, that it jumps (if you are in the diff-range between 0-128).
I can not figure out where the problem sits. Any idea how to get this to work correctly?
Here's what I've done so far: http://jsfiddle.net/yckart/rKW3f/
// something simple to get the current scroll direction
// false === down | true === up
var scrollDir = (function (oldOffset, lastOffset, oldDir) {
return function (offset) {
var dir = offset < oldOffset;
if (dir !== oldDir) lastOffset = offset;
oldOffset = offset;
oldDir = dir;
return {dir: dir, last: lastOffset};
};
}());
var header = document.querySelector('header');
var height = header.clientHeight;
addEventListener('scroll', function () {
var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
var dir = scrollDir(scrollY);
var diff = dir.last-scrollY;
var max = Math.max(-height, Math.min(height, diff));
header.style.top = (dir.dir ? max-height : max) + 'px';
});
Another problem is, that if the scroll-direction was changed the first time, nothing happens. However, this could be fixed with an interval, or else.
I believe this is exactly what you want:
var header = $('header'),
headerHeight = header.height(),
treshold = 0,
lastScroll = 0;
$(document).on('scroll', function (evt) {
var newScroll = $(document).scrollTop(),
diff = newScroll-lastScroll;
// normalize treshold range
treshold = (treshold+diff>headerHeight) ? headerHeight : treshold+diff;
treshold = (treshold < 0) ? 0 : treshold;
header.css('top', (-treshold)+'px');
lastScroll = newScroll;
});
Demo on: http://jsfiddle.net/yDpeb/
Try this out:- http://jsfiddle.net/adiioo7/rKW3f/7/
JS:-
var scrollDir = (function (oldOffset, lastOffset, oldDir) {
return function (offset) {
var dir = offset < oldOffset;
if (dir !== oldDir) {
lastOffset = offset;
} else {
offset = offset - height;
}
oldOffset = offset;
oldDir = dir;
return {
dir: dir,
last: lastOffset
};
};
}());
var header = document.querySelector('header');
var height = header.clientHeight;
$(window).scroll(function () {
var scrollY = $(window).scrollTop();
var dir = scrollDir(scrollY);
var diff = dir.last - scrollY;
var max = Math.max(-height, Math.min(height, diff));
max = (dir.dir ? max - height : max);
max = scrollY<height?0:max;
$('header').data('size', 'small');
$('header').stop().animate({
top: max
}, 600);
});
Sargo Darya's answer above is exacty what i was looking for but I found a bug with Webkits inertia scrolling so I made a fix:
// Scrolling Header
var header = $('header'),
headerHeight = header.height(),
offset = 0,
lastPos = 0;
$(document).on('scroll', function(e) {
var newPos = $(document).scrollTop(),
pos = newPos-lastPos;
if (offset+pos>headerHeight) {
offset = headerHeight;
} else if (newPos < 0){ // webkit inertia scroll fix
offset = 0;
} else {
offset = offset+pos;
};
if (offset < 0) {
offset = 0;
} else {
offset = offset;
};
header.css('top', (-offset)+'px');
lastPos = newPos;
});
Adding one line fixed it. If - if scroll position is lower than 0, set header offset at 0.
Demo based on Sargo Darya's - http://jsfiddle.net/edwardomni/D58vx/4/
how to determine, using jquery, if the element is visible on the current page view. I'd like to add a comment functionality, which works like in facebook, where you only scroll to element if it's not currently visible. By visible, I mean that it is not in the current page view, but you can scroll to the element.
Live Demo
Basically you just check the position of the element to see if its within the windows viewport.
function checkIfInView(element){
var offset = element.offset().top - $(window).scrollTop();
if(offset > window.innerHeight){
// Not in view so scroll to it
$('html,body').animate({scrollTop: offset}, 1000);
return false;
}
return true;
}
Improving Loktar's answer, fixing the following:
Scroll up
Scroll to a display:none element (like hidden div's etc)
function scrollToView(element){
var offset = element.offset().top;
if(!element.is(":visible")) {
element.css({"visibility":"hidden"}).show();
var offset = element.offset().top;
element.css({"visibility":"", "display":""});
}
var visible_area_start = $(window).scrollTop();
var visible_area_end = visible_area_start + window.innerHeight;
if(offset < visible_area_start || offset > visible_area_end){
// Not in view so scroll to it
$('html,body').animate({scrollTop: offset - window.innerHeight/3}, 1000);
return false;
}
return true;
}
After trying all these solutions and many more besides, none of them satisfied my requirement for running old web portal software (10 years old) inside IE11 (in some compatibility mode). They all failed to correctly determine if the element was visible. However I found this solution. I hope it helps.
function scrollIntoViewIfOutOfView(el) {
var topOfPage = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
var heightOfPage = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
var elY = 0;
var elH = 0;
if (document.layers) { // NS4
elY = el.y;
elH = el.height;
}
else {
for(var p=el; p&&p.tagName!='BODY'; p=p.offsetParent){
elY += p.offsetTop;
}
elH = el.offsetHeight;
}
if ((topOfPage + heightOfPage) < (elY + elH)) {
el.scrollIntoView(false);
}
else if (elY < topOfPage) {
el.scrollIntoView(true);
}
}
I made a slightly more generic version of digitalPBK's answer that minimally scrolls an element contained within a div or some other container (including the body). You can pass DOM elements or selectors to the function, as long as the element is somehow contained within the parent.
function scrollToView(element, parent) {
element = $(element);
parent = $(parent);
var offset = element.offset().top + parent.scrollTop();
var height = element.innerHeight();
var offset_end = offset + height;
if (!element.is(":visible")) {
element.css({"visibility":"hidden"}).show();
var offset = element.offset().top;
element.css({"visibility":"", "display":""});
}
var visible_area_start = parent.scrollTop();
var visible_area_end = visible_area_start + parent.innerHeight();
if (offset-height < visible_area_start) {
parent.animate({scrollTop: offset-height}, 600);
return false;
} else if (offset_end > visible_area_end) {
parent.animate({scrollTop: parent.scrollTop()+ offset_end - visible_area_end }, 600);
return false;
}
return true;
}
You can take a look at his awesome link from the jQuery Cookbook:
Determining Whether an Element Is Within the Viewport
Test if Element is contained in the Viewport
jQuery(document).ready(function() {
var viewportWidth = jQuery(window).width(),
viewportHeight = jQuery(window).height(),
documentScrollTop = jQuery(document).scrollTop(),
documentScrollLeft = jQuery(document).scrollLeft(),
$myElement = jQuery('#myElement'),
elementOffset = $myElement.offset(),
elementHeight = $myElement.height(),
elementWidth = $myElement.width(),
minTop = documentScrollTop,
maxTop = documentScrollTop + viewportHeight,
minLeft = documentScrollLeft,
maxLeft = documentScrollLeft + viewportWidth;
if (
(elementOffset.top > minTop && elementOffset.top + elementHeight < maxTop) &&
(elementOffset.left > minLeft && elementOffset.left + elementWidth < maxLeft)
) {
alert('entire element is visible');
} else {
alert('entire element is not visible');
}
});
Test how much of the element is visible
jQuery(document).ready(function() {
var viewportWidth = jQuery(window).width(),
viewportHeight = jQuery(window).height(),
documentScrollTop = jQuery(document).scrollTop(),
documentScrollLeft = jQuery(document).scrollLeft(),
$myElement = jQuery('#myElement'),
verticalVisible, horizontalVisible,
elementOffset = $myElement.offset(),
elementHeight = $myElement.height(),
elementWidth = $myElement.width(),
minTop = documentScrollTop,
maxTop = documentScrollTop + viewportHeight,
minLeft = documentScrollLeft,
maxLeft = documentScrollLeft + viewportWidth;
function scrollToPosition(position) {
jQuery('html,body').animate({
scrollTop : position.top,
scrollLeft : position.left
}, 300);
}
if (
((elementOffset.top > minTop && elementOffset.top < maxTop) ||
(elementOffset.top + elementHeight > minTop && elementOffset.top +
elementHeight < maxTop))
&& ((elementOffset.left > minLeft && elementOffset.left < maxLeft) ||
(elementOffset.left + elementWidth > minLeft && elementOffset.left +
elementWidth < maxLeft)))
{
alert('some portion of the element is visible');
if (elementOffset.top >= minTop && elementOffset.top + elementHeight
<= maxTop) {
verticalVisible = elementHeight;
} else if (elementOffset.top < minTop) {
verticalVisible = elementHeight - (minTop - elementOffset.top);
} else {
verticalVisible = maxTop - elementOffset.top;
}
if (elementOffset.left >= minLeft && elementOffset.left + elementWidth
<= maxLeft) {
horizontalVisible = elementWidth;
} else if (elementOffset.left < minLeft) {
horizontalVisible = elementWidth - (minLeft - elementOffset.left);
} else {
horizontalVisible = maxLeft - elementOffset.left;
}
var percentVerticalVisible = (verticalVisible / elementHeight) * 100;
var percentHorizontalVisible = (horizontalVisible / elementWidth) * 100;
if (percentVerticalVisible < 50 || percentHorizontalVisible < 50) {
alert('less than 50% of element visible; scrolling');
scrollToPosition(elementOffset);
} else {
alert('enough of the element is visible that there is no need to scroll');
}
} else {
// element is not visible; scroll to it
alert('element is not visible; scrolling');
scrollToPosition(elementOffset);
}
The following code helped me achieve the result
function scroll_to_element_if_not_inside_view(element){
if($(window).scrollTop() > element.offset().top){
$('html, body').animate( { scrollTop: element.offset().top }, {duration: 400 } );
}
}
Here is the solution I came up with, working both up and down and using only Vanilla Javascript, no jQuery.
function scrollToIfNotVisible(element) {
const rect = element.getBoundingClientRect();
// Eventually an offset corresponding to the height of a fixed navbar for example.
const offset = 70;
let scroll = false;
if (rect.top < offset) {
scroll = true;
}
if (rect.top > window.innerHeight) {
scroll = true;
}
if (scroll) {
window.scrollTo({
top: (window.scrollY + rect.top) - offset,
behavior: 'smooth'
})
}
}
There is a jQuery plugin which allows us to quickly check if a whole element (or also only part of it) is within the browsers visual viewport regardless of the window scroll position. You need to download it from its GitHub repository:
Suppose to have the following HTML and you want to alert when footer is visible:
<section id="container">
<aside id="sidebar">
<p>
Scroll up and down to alert the footer visibility by color:
</p>
<ul>
<li><span class="blue">Blue</span> = footer <u>not visible</u>;</li>
<li><span class="yellow">Yellow</span> = footer <u>visible</u>;</li>
</ul>
<span id="alert"></span>
</aside>
<section id="main_content"></section>
</section>
<footer id="page_footer"></footer>
So, add the plugin before the close of body tag:
<script type="text/javascript" src="js/jquery-1.12.0.min.js"></script>
<script type="text/javascript" src="js/jquery_visible/examples/js/jq.visible.js"></script>
After that you can use it in a simple way like this:
<script type="text/javascript">
jQuery( document ).ready(function ( $ ) {
if ($("footer#page_footer").visible(true, false, "both")) {
$("#main_content").css({"background-color":"#ffeb3b"});
$("span#alert").html("Footer visible");
} else {
$("#main_content").css({"background-color":"#4aafba"});
$("span#alert").html("Footer not visible");
}
$(window).scroll(function() {
if ($("footer#page_footer").visible(true, false, "both")) {
$("#main_content").css({"background-color":"#ffeb3b"});
$("span#alert").html("Footer visible");
} else {
$("#main_content").css({"background-color":"#4aafba"});
$("span#alert").html("Footer not visible");
}
});
});
</script>
Here a demo
No-JQuery version.
The particular case here is where the scroll container is the body (TBODY, table.body) of a TABLE (scrolling independently of THEAD). But it could be adapted to any situation, some simpler.
const row = table.body.children[ ... ];
...
const bottomOfRow = row.offsetHeight + row.offsetTop ;
// if the bottom of the row is in the viewport...
if( bottomOfRow - table.body.scrollTop < table.body.clientHeight ){
// ... if the top of the row is in the viewport
if( row.offsetTop - table.body.scrollTop > 0 ){
console.log( 'row is entirely visible' );
}
else if( row.offsetTop - table.body.scrollTop + row.offsetHeight > 0 ){
console.log( 'row is partly visible at top')
row.scrollIntoView();
}
else {
console.log( 'top of row out of view above viewport')
row.scrollIntoView();
}
}
else if( row.offsetTop - table.body.scrollTop < table.body.clientHeight ){
console.log( 'row is partly visible at bottom')
row.scrollIntoView();
}
else {
console.log( 'row is out of view beneath viewport')
row.scrollIntoView();
}
I think this is the complete answer. An elevator must be able to go both up and down ;)
function ensureVisible(elementId, top = 0 /* set to "top-nav" Height (if you have)*/) {
let elem = $('#elementId');
if (elem) {
let offset = elem.offset().top - $(window).scrollTop();
if (offset > window.innerHeight) { // Not in view
$('html,body').animate({ scrollTop: offset + top }, 1000);
} else if (offset < top) { // Should go to top
$('html,body').animate({ scrollTop: $(window).scrollTop() - (top - offset) }, 1000);
}
}
}