I have it right now so that when you scroll down a fixed text will appear. However, the script running it is currently initiating when the viewport is scrolled to the <span>. How can I make it so that the script starts when you're, say 100px, above the <span>
I've tried using a <div> and positioning it where I want so that the script picks that up instead of the <span> however, that just adds unwanted blank space.
<div class="invis"></div>
.invis { height: 100px; visibility: hidden; }
Code: http://jsfiddle.net/suLLL/1/
$(window).scroll(checkY);
function checkY() {
//save this value so we dont have to call the function everytime
var top = $(window).scrollTop();
$(".title").each(function () {
var target = $(this).closest(".content");
var tTop = target.offset().top;
var tBottom = target.offset().top + target.outerHeight();
if (top >= tTop && top <= tBottom) {
console.log("Show");
$(this).show();
} else {
console.log("Hide");
$(this).hide();
}
});
}
checkY();
You could remove the height from the 'tTop' variable:
var someVal = 100;
var tTop = target.offset().top - someVal;
Related
I have huge sidebar element and when the page is scrolled sidebar point to the current element that is in a viewport. But sometimes active element is out of sidebar visible space i.e below or above borders. And then the user needs to scroll manually to be able to see active element.
I want to try use logic for determining if the active element is out sidebar visible space and auto scroll if needed.
$(window).on('scroll', function () {
var scrollTop = $(this).scrollTop();
var container = $('#sectionMenu');
var containerHeight = container.height();
$(data).each(function () {
var topDistance = $(this).offset().top - 250;
var id = $(this).attr('id');
var elem = $('#_' + id);
if ((topDistance) < scrollTop && (topDistance + $(this).height() * 0.95) > scrollTop) {
if (autoScrollFlag) {
if (!elem.hasClass('sideBarActive')) {
var scrollPosition = elem.offset().top - container.offset().top;
removeActiveMenuItems(data);
elem.addClass('sideBarActive');
if (containerHeight < scrollPosition) {
// TODO automated scroll
}
}
}
autoScrollFlag = 1;
}
});
});
The solution that has worked for me was like this.
if (containerHeight < scrollPosition) {
container.animate({
scrollTop: '+=100px'
}, 800);
}
I'm trying to get the div to snap to the center of the viewport, right now it just snaps to the top. I was trying to put an offset of 50% but can only get it in px's.
EDIT
I added a new fiddle where I tried to include $(window).scrollTop() / 2)
http://jsfiddle.net/kZY9R/84/
$("#item").offset().top - 100
var body = $("html, body");
var items = $(".item");
var animating = false;
$(window).scroll(function() {
clearTimeout($.data(this, 'scrollTimer'));
if (!animating) {
$.data(this, 'scrollTimer', setTimeout(function() {
items.each(function(key, value) {
if ($(value).offset().top > $(window).scrollTop()) {
animating = true;
$(body).stop().animate( { scrollTop: $(value).offset().top }, 1000,'swing');
setTimeout(function() { animating = false; }, 2000);
return false;
}
});
}, 50));
}
});
I found this:
$('html, body').animate({scrollTop: $('#your-id').offset().top -100 }, 'slow');
Source: Run ScrollTop with offset of element by ID
Here's the trick to keep your viewport centralized on a particular div.
Prerequisites
You need to take into account the following three criteria to be able to centralize the viewport on a given item:
height of the last item that appeared on the viewport.
The distance of the last item from the top of the page, i.e. the offset().top of the item.
The height value of the viewport (i.e the window object).
Calculating Vertical Position of the Item
The required scrollTop value for the window can be calculated as in the following:
var scrollValue = itemOffset // offset of the item from the top of the page
- .5 * windowHeight // half the height of the window
+ .5 * itemHeight; // half the height of the item
You are basically, moving the top of your viewport to the item under view's top offset initially. This, as you've already experienced, snaps the item to the top of the window.
The real magic part comes when you subtract half of the window's height to go halfway along it vertically, and then shifting your view back down by adding half the item's height. This makes the item appear vertically centralized with regards to the viewport.
Note:
To be able to query the last item that appeared on the viewport, you have to iterate over all of the elements that have a top offset value (i.e. offset().top) less than or equal to that of the window's scrollTop value:
$.each($('.item'), function(i, value) {
if ($(viewport).scrollTop() >= $(this).offset().top) {
lastItemInView = $(this);
}
});
With the above, the lastItemInView variable will always end up with the last element visible in the window.
Demo
Not sure if you figured this out yet or not but I took some code from this answer (How to tell if a DOM element is visible in the current viewport?) that shows how to tell if an element is visible in the view port.
Using that I modified your code to loop through each item and find the first visible one in the viewport and then center that one also factoring in the margin-top you have. Let me know if this helps!
Fiddle: http://jsfiddle.net/kZY9R/86/
var body = $("html, body");
var items = $(".item");
var animating = false;
$(window).scroll(function() {
clearTimeout($.data(this, 'scrollTimer'));
if (!animating) {
$.data(this, 'scrollTimer', setTimeout(function() {
items.each(function(key, value) {
if (elementInViewport(value)) {
animating = true;
var margin = parseInt($(value).css('margin-top'));
$('html,body').animate({
scrollTop: $(value).offset().top - ($(window).height() + margin - $(value).outerHeight(true)) / 2
}, 200);
setTimeout(function() {
animating = false;
}, 2000);
return false;
}
});
}, 50));
}
});
function elementInViewport(el) {
var top = el.offsetTop;
var left = el.offsetLeft;
var width = el.offsetWidth;
var height = el.offsetHeight;
while (el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
left += el.offsetLeft;
}
return (
top < (window.pageYOffset + window.innerHeight) &&
left < (window.pageXOffset + window.innerWidth) &&
(top + height) > window.pageYOffset &&
(left + width) > window.pageXOffset
);
}
I have a series of divs that are 100% height with a scroll to function that takes you to the next div out of the viewport on background click. However, if the next div is already slightly in the viewport the whole thing is counted as being visible and the scroll to bypasses it. Can anyone offer direction on how to get the script to scroll to the div even if it's partially in the viewport already?
Codepen here.
If you begin scrolling slightly in the codepen and then click on the background you'll see that it doesnt scroll you to the div that's already in the viewport but the div after that.
$(document).ready(function() {
// get initial nav height
var $window = $(window);
var wst = $window.scrollTop();
var th = $('div.top').height();
var currentSlide = $('#wrapper').data( 'current-slide', $('div.slide').eq(0) );
$('div.scroll_images').css({ height: 'auto', overflow: 'visible', top: 0 });
$('div.scroll_images div.inner').css({ position: 'absolute', top: 0 });
$('div.slide').each(function() {
$(this).css('padding',function() {
return (($(window).height()-$(this).height())/2)+'px 0'
});
});
// scrollto for click on slide
jQuery.fn.scrollTo = function(hash) {
$this = $(this);
st = $this.offset().top - th; // subtract nav height
$('html, body').animate({ scrollTop: st }, 550
);
}
$('#wrapper').click(function(e){
//get the current slide index from the body tag.
$this = currentSlide.data( 'current-slide' );
$next = $(".slide:below-the-fold");
if($next.length) {
$next.scrollTo($next.attr('id'));
//Save the next slide as the current.
$('#wrapper').data( 'current-slide', $next );
} else {
//Throw us back to the top.
$('div.slide:first').scrollTo($('div.slide:first').attr('id'));
//Save the first slide as the first slide, which
//Cycles us back to the top.
$('#wrapper').data( 'current-slide', $('div.slide:first'));
}
})
//Images fade in
$('img').hide();
$('img').each(function(i) {
if (this.complete) {
$(this).fadeIn();
} else {
$(this).load(function() {
$(this).fadeIn();
});
}
});
//Stop links affecting scroll function
$("a").click(function(e) {
e.stopPropagation();
});
});
(function($) {
$.belowthefold = function(element, settings) {
var fold = $(window).height() + $(window).scrollTop();
return fold <= $(element).offset().top - settings.threshold;
};
$.extend($.expr[':'], {
"below-the-fold": function(a, i, m) {
return $.belowthefold(a, {threshold : 0});
}
});
})(jQuery);
Here's what I might try to do: go through each div in the series. Find the div who's offset() is closest to $(window).scrollTop(). Now, find the next() div after the "current" one and scroll to it.
For comparing the offset() of each div, try something like this:
var closest = $('[selector]:first');
$('[selector]').each(function() {
var oldDistance = Math.abs(closest.offset() - $(window).scrollTop());
var newDistance = Math.abs($(this).offset() - $(window).scrollTop());
if(newDistance < oldDistance) {
closest = $(this);
}
}
So I basically want the script to start at the top of "mini" div but can't get it to work right.
#mini {
width: 100%;
padding-top: 300px;}
var tTop = $("#mini").outerHeight(true);
Full script:
$(window).scroll(checkY);
function checkY() {
//save this value so we dont have to call the function everytime
var top = $(window).scrollTop();
$(".title").each(function () {
var target = $(this).closest(".content");
var tTop = $("#mini").outerHeight(true);
var tBottom = target.offset().top + target.outerHeight();
if (top >= tTop && top <= tBottom) {
console.log("Show");
$(this).show();
} else {
console.log("Hide");
$(this).hide();
}
});
}
checkY();
Why not setting the mini style to
position:relative;
and the inner div to
position: absolute;
top:0
I'm having a hard time finding a Javascript piece of code to dynamically show the Back to Top button when the user has scrolled, lets say, more than 1000 pixels. All examples use jQuery, and I can't use jQuery. Any help will be very appreciated.
Set the CSS when pageOffset is a certain point (in a window.onscroll event):
window.onscroll = function()
{
if(pageOffset >= 1000)
{
document.getElementById('backToTopID').style.visibility="visible"
}
};
something more full would be:
window.onscroll = function()
{
if(pageOffset >= 1000)
{
document.getElementById('backToTopID').style.visibility="visible"
}else
{
document.getElementById('backToTop').style.visibility="hidden";
}
};
DEMO
JavaScript using Window.onscroll
var appended = false, bookmark = document.createElement("div");
bookmark.id = "arrowUp";
bookmark.innerHTML = "<a href=\"#\" title=\"Top of the page.\">↑<\/a>";
onscroll = function() {
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
if (scrollTop > 500) {
if (!appended) {
document.body.appendChild(bookmark);
appended = true;
}
} else {
if (appended) {
document.body.removeChild(bookmark);
appended = false;
}
}
};
source
https://developer.mozilla.org/en-US/docs/Web/API/window.onscroll
demo link
http://jsfiddle.net/MA4dC/
This is how I do it. To show back to top button when user scrolls more than 150 pixels down from top of document.
//how to show back to top button when user scrolls more than 150 pixels down from top of document.
var toTopButton = document.querySelector("a");
toTopButton.style.display = "none";//by default should be hidden
document.querySelector('body').onscroll = function(){//whenever they scroll
if (window.scrollY > 150)//if scroll is 150px from top
toTopButton.style.display = "block";//if they scroll down, show
else
toTopButton.style.display = "none";//if they scroll up, hide
};
html {scroll-behavior: smooth;}
a {
background-color: #f00;
position: fixed;
bottom: 10px;
right: 10px;
}
<html>
back to top
<body id="top">
text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>
</body>
<html>
OR to show back to top button when user scrolls more than 150 pixels up from bottom of document.
//how to show back to top button when user scrolls more than 150 pixels up from bottom of document.
var toTopButton = document.querySelector("a");
toTopButton.style.display = "none";
document.querySelector('body').onscroll = function(){
if (window.innerHeight + 150 < document.body.offsetHeight)//if document long enough
if (window.scrollY + window.innerHeight > document.body.offsetHeight - 150)//if scroll is 150px from bottom (if 'bottom of what we are looking at' is > than 'bottom of document - 150px earlier)
toTopButton.style.display = "block";
else
toTopButton.style.display = "none";
};
html {scroll-behavior: smooth;}
a {
background-color: #f00;
position: fixed;
bottom: 10px;
right: 10px;
}
<html>
back to top
<body id="top">
text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>
</body>
<html>
Simple but working.
CSS:
#scrollToTop { visibility: hidden; }
JavaScript:
// Show/Hide the button
window.onscroll = function() {
var pageOffset = document.documentElement.scrollTop || document.body.scrollTop,
btn = document.getElementById('scrollToTop');
if (btn) btn.style.visibility = pageOffset > 450 ? 'visible' : 'hidden';
};