Calculating & setting scroll speed of object in viewport - javascript

I have image I am scrolling within a div.
It make sure the image is visible I am using
var isVisible = (
threshold.top >= -39 &&
threshold.bottom <= (window.innerHeight || document.documentElement.clientHeight)
);
What I am trying to do now is make sure that once the element is visible it is able to completely finish scrolling before going out of the view port.
I am thinking I can do this by effecting the speed value based on the the distance of the element from the top on the window. But I am having a very hard time doing this.
I am using .getBoundingClientRect() to get the distance the element is from the top of the viewport:
var threshold = document.getElementById('page-feature').getBoundingClientRect();
var thresholdY = threshold.top;
Below is my code so far:
function scrollImageInViewport() {
var threshold = document.getElementById('page-feature').getBoundingClientRect();
var thresholdY = threshold.top;
var isVisible = (
threshold.top >= -39 &&
threshold.bottom <= (window.innerHeight || document.documentElement.clientHeight)
);
if (isVisible && window.innerWidth > 550) {
scrollDir(thresholdY);
}
}
function scrollUp(thresholdY) {
if (thresholdCounter < maxScrollNegative) {
return;
} else {
pageScroll.setAttribute('style', '-webkit-transform:translate3d(0,' + (--thresholdCounter *speed) + 'px,0); -ms-transform:translate3d(0,' + (--thresholdCounter *speed) + 'px,0); transform:translate3d(0,' + (--thresholdCounter *speed) + 'px,0);');
}
};
function scrollDown(thresholdY) {
if (thresholdCounter > maxScrollPositive) {
return;
} else {
pageScroll.setAttribute('style', '-webkit-transform:translate3d(0,' + (++thresholdCounter *speed) + 'px,0); -ms-transform:translate3d(0,' + (++thresholdCounter *speed) + 'px,0); transform:translate3d(0,' + (++thresholdCounter *speed) + 'px,0);');
}
};
function scrollToTop(){
initScroll();
pageScroll.setAttribute('style', 'transform:translate3d(0,0,0);');
thresholdCounter = 0;
};
function scrollDir(thresholdY) {
var scroll = window.scrollY;
if(scroll > position) {
distanceFromTop(thresholdY);
scrollUp(thresholdY);
} else if (scroll < position ){
scrollDown(thresholdY);
}
position = scroll;
};
function distanceFromTop(thresholdY) {
if (thresholdY > 0) {
`enter code here`//set speed as distance from top /px of not shown content
speed = (scrollImageHeight - scrollVisibleHeight) / thresholdY;
}
};
function initScroll(){
position = window.scrollY;
pageScroll = document.getElementById('page-scroll');
scrollImageHeight = pageScroll.offsetHeight; //total height of scroll image
pagePanel = document.getElementById("pagePanel");
pageStyle = window.getComputedStyle(pagePanel,"");
size = pageStyle.getPropertyValue("height");
scrollVisibleHeight = parseInt(size, 10);//visible height of scroll image
scrollImageEnd = scrollImageHeight - scrollVisibleHeight;
maxScrollNegative = -scrollImageEnd / speed;
}
var speed;
var thresholdCounter = 0;
var maxScrollPositive = 0;
var position,
pageScroll,
scrollImageHeight,
pagePanel,
pageStyle,
size,
scrollVisibleHeight,
scrollImageEnd,
maxScrollNegative;
window.addEventListener('resize', scrollToTop);
document.addEventListener('scroll', scrollImageInViewport);
window.addEventListener('load', initScroll);

This is what I ended up with:
var featurePage = document.getElementById('page-feature')
var pageScroll = document.getElementById('page-scroll');
var startP, // where animation needs to begin
endP, // where animation needs to end
diff; // visible element size
function getElementOffset(){ //init
var de = document.documentElement;
var box = featurePage.getBoundingClientRect();
var top = box.top + window.pageYOffset - de.clientTop;
var bottom = box.bottom + window.pageYOffset - de.clientTop;
var winHight = window.innerHeight;
diff = bottom - top;
var elPadding = (winHight - diff);
startP = top - elPadding;
endP = bottom - elPadding;
scrollImage()
}
function scrollImage(){
var scrollImageHeight = pageScroll.offsetHeight;
var scrollPos = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
var s1 = scrollPos - startP;
var realPos = -s1/diff;
var lengthLeft = scrollImageHeight - (diff)
if ( realPos < 0.09 && realPos > -1){
pageScroll.setAttribute('style', '-webkit-transform:translate3d(0,' + (realPos * lengthLeft) + 'px,0); -ms-transform:translate3d(0,' + (realPos *lengthLeft) + 'px,0); transform:translate3d(0,' + (realPos *lengthLeft) + 'px,0);');
}
}
window.addEventListener('resize', getElementOffset);
document.addEventListener('scroll', getElementOffset);

Related

Animate three card depends on scrolling value

I have three card in horizontal, i just want animate them like this https://www.bluelabellabs.com/work/delve/ (the Result Section)
My JS Code:
`window.addEventListener('scroll', () => {
const cardOne = document.getElementById("box_one")
const cardTwo = document.getElementById("box_two")
const cardThree = document.getElementById("box_three")
const scrollYValue = window.scrollY;
$(window).scroll(function () {
if ($(window).scrollTop() > $('body').height() / 2) {
const cardOne = document.getElementById("box_one")
const cardTwo = document.getElementById("box_two")
const cardThree = document.getElementById("box_three")
const scrollYValue = window.scrollY;
$(window).scroll(function() {
var position = $(window).scrollTop();
var scroll = $(window).scrollTop();
// console.log(scroll, position);
if (scroll >= position) {
console.log("Up");
cardOne.style.transform = "translate3d(0px, " + -scrollYValue / 200 + "em, 0px)",
cardTwo.style.transform = "translate3d(0px, " + -scrollYValue / 600 + "em, 0px)",
cardThree.style.transform = `translateY(${scrollYValue / 30}px)`
} else if (scroll <= position) {
console.log("back");
cardOne.style.transform = "translate3d(0px, " + scrollYValue + "px, 0px)",
cardTwo.style.transform = `translateY(${-scrollYValue / 90}px)`
cardThree.style.transform = `translateY(${-scrollYValue / 30}px)`
}
position = scroll;
});
}
});
})`

How to prevent randomly generated images from overlapping using Javascript

I'm trying to spawn randomly generated targets on the screen using a function to copy an invisible image of the target to be spawned at a random place within the screen using window object properties.
For this to happen I think the image have to have position set to absolute, but then several images may be spawned in a way that they will overlap, how can I prevent this from happening?
The div element where I copy my first image and also store the other copies.
<div id="targetsDiv">
<img src="target2.png" alt="target_shot" class="target" />
</div>
Inside the script:
var x_pixels = window.innerWidth - 180;
var y_pixels = window.innerHeight - 180;
var x_midScreen = window.innerWidth / 2;
var y_midScreen = window.innerHeight / 2;
var xRandom = Math.floor(Math.random()*x_pixels) +1;
var yRandom = Math.floor(Math.random()*y_pixels) +1;
var targetCollection = document.getElementById("targetsDiv");
var targetCopy = targetCollection.innerHTML
var targetList = document.getElementsByClassName("target");
targetList[0].style.display = "none";
var targetNr = 1;
var numberOfSpawns = 3;
function spawnTargets () {
while (targetNr <= numberOfSpawns) {
if ((xRandom < x_midScreen - 126 || xRandom > x_midScreen + 26) || (yRandom < y_midScreen - 126 || yRandom > y_midScreen + 26)) {
targetCollection.innerHTML += targetCopy;
targetList[targetNr].style.left = xRandom + "px";
targetList[targetNr].style.top = yRandom + "px";
targetNr++;
}
xRandom = Math.floor(Math.random()*x_pixels) +1;
yRandom = Math.floor(Math.random()*y_pixels) +1;
}
}
PS: I appreciate all help, tips and tweaks that you guys provide:) Thanks for helping
The area you want to exclude in the centre of the screen is rather large, and on my little laptop, there isn't even any room to still show the random positioned images.
But anyway, this piece of code should do the job -- I added some infinite loop protection which on my PC was a life-saver:
HTML (added style attribute)
<div id="targetsDiv">
<img src="target2.png" alt="target_shot" class="target"
style="visibility:hidden"/>
</div>
JavaScript:
window.addEventListener('load', function () {
var targetCollection = document.getElementById("targetsDiv");
var template = document.getElementsByClassName("target")[0];
var targetWidth = template.offsetWidth;
var targetHeight = template.offsetHeight;
var x_pixels = window.innerWidth - targetWidth;
var y_pixels = window.innerHeight - targetHeight;
var x_midScreen = window.innerWidth / 2;
var y_midScreen = window.innerHeight / 2;
function spawnTargets (numberOfSpawns) {
var targets = [];
var count = 0; // infinite recursion protection
for (var i = 0; i < numberOfSpawns; i++) {
do {
do {
var x = Math.floor(Math.random()*x_pixels);
var y = Math.floor(Math.random()*y_pixels);
if (count++ > 200) {
console.log('give up');
return;
}
} while ((x >= x_midScreen-450 && x <= x_midScreen+300) && (y >= y_midScreen-350 || y <= y_midScreen+200));
for (var j = 0; j < i; j++) {
if (x >= targets[j].x - targetWidth && x <= targets[j].x + targetWidth &&
y >= targets[j].y - targetHeight && y <= targets[j].y + targetHeight) break; // not ok!
}
} while (j < i);
targets.push({x, y});
img = document.createElement('img');
img.src = template.src;
img.setAttribute('width', targetWidth + 'px');
img.setAttribute('height', targetHeight + 'px');
img.className = template.className;
targetCollection.appendChild(img);
img.style.left = x + "px";
img.style.top = y + "px";
}
}
spawnTargets(3);
});

Scroll then snap to top not unsnapping

I'm trying to create snap to top divs that cover the entire page and I have it working, it's just that after they snap to the top they don't unsnap and stay fixed to the top. I'm using the answer given by mu is too short from this previous question scroll then snap to top but I can't get it to unsnap.
Here's a jsbin of the code.
var h = 0;
var notif;
var notif2;
var init;
var docked = false;
function getSize() {
h = window.innerHeight;
notif = document.getElementById("notif");
notif2 = document.getElementById("notif2");
var fl = document.getElementById("floater");
init = notif.scrollTop;
notif.style.top = "" + h + "px";
var h2 = h / 2;
fl.style.marginTop = "" + h2 + "px";
notif.style.height = "" + h + "px";
var twoh = 3 * h2;
notif2.style.top = "" + h + "px";
notif2.style.height = "" + h + "px";
}
window.onscroll = function() {
if (!docked && (notif.offsetTop - document.body.scrollTop < 0)) {
console.log("in loop");
notif.style.top = 0;
notif.style.position = 'fixed';
notif2.style.marginTop = "" + h + "px";
docked = true;
} else if (docked && document.body.scrollTop <= init) {
notif.style.position = 'block';
while (notif.style.top <= h) {
var ab = Math.abs(notif.offsetTop)
var ab2 = Math.abs(document.body.scrollTop);
notif.style.top = init + 'px';
}
if (notif.style.top == h || notif.style.top == h - 1) {
docked = false;
}
}
};
<body onload="getSize()">
<div class="contain">
<div id="floater">
<h1 class="white">Hello, World</h1>
Link 1 Link 2
</div>
</div>
<div class="announcements" id="notif">
Please cover the previous text on the page. If this works i will be really excited.
</div>
<div class="announcements2" id="notif2">
Cover the white page.
</div>
</body>
Save the values used before you set these, and reset them when you "un-dock". Simply setting "docked" to show that you're un-docked is not enough.
This code is an example of how to do that from your staring point.
Here's how I saved it and got something like the behaviour you mention
var h = 0;
var notif;
var notif2;
var init;
var docked = false;
// holding space for reset values
var holdNotifyStyleTop;
var holdNotifyOffsetTop;
var holdNotif2StyleMarginTop;
function getSize() {
h = window.innerHeight;
notif = document.getElementById("notif");
notif2 = document.getElementById("notif2");
var fl = document.getElementById("floater");
init = notif.offsetTop;
notif.style.top = ""+h+"px";
var h2 = h/2;
fl.style.marginTop = ""+h2+"px";
notif.style.height = ""+h+"px";
var twoh = 3*h2;
notif2.style.top=""+h+"px";
notif2.style.height = ""+h+"px";
}
window.onscroll = function () {
if (!docked && (notif.offsetTop - document.body.scrollTop < 0)) {
console.log("--- DOCKING ---");
// save current values
holdNotifyStyleTop = notif.style.top;
holdNotifyOffsetTop = notif.offsetTop;
holdNotif2StyleMarginTop = notif2.style.marginTop;
notif.style.top = 0;
notif.style.position = 'fixed';
notif2.style.marginTop=""+h+"px";
docked = true;
} else if (docked && document.body.scrollTop <= init) {
console.log("--- Un-DOCKING ---");
notif.style.top = holdNotifyStyleTop;
notif.style.position = 'relative';
notif2.style.marginTop=holdNotif2StyleMarginTop;
notif.offsetTop = holdNotifyOffsetTop;
docked = false;
}
};

Slide header up if you scroll down and vice versa

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/

Scroll if element is not visible

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);
}
}
}

Categories

Resources