Scroll a specific element inside container using JS or jQuery - javascript

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

Related

Divs don't stop following scroll at footer

I tried a lot of solutions but I cant make the divs stop following the scroll at the footer.
Here is my code to make the divs follow the scroll (colderecha and colizquierda are my divs that follow the scroll):
$(document).ready(function () {
var top = $('#colizquierda').offset().top - parseFloat($('#colizquierda').css('marginTop').replace(/auto/, 0));
$(window).scroll(function (event) {
var y = $(this).scrollTop();
//if y > top, it means that if we scroll down any more, parts of our element will be outside the viewport
//so we move the element down so that it remains in view.
if (y >= top) {
var difference = y - top;
$('#colizquierda').css("top",difference);
}
});
});
$(document).ready(function () {
var top = $('#colderecha').offset().top - parseFloat($('#colderecha').css('marginTop').replace(/auto/, 0));
$(window).scroll(function (event) {
var y = $(this).scrollTop();
//if y > top, it means that if we scroll down any more, parts of our element will be outside the viewport
//so we move the element down so that it remains in view.
if (y >= top) {
var difference = y - top;
$('#colderecha').css("top",difference);
}
});
});
What I have tried:
$(document).scroll(function() {
checkOffset();
});
function checkOffset() {
if ($('#colizquierda').offset().top + $('#colizquierda').height() >= $('#footer').offset().top - 10)
$('#colizquierda').css('position', 'absolute');
if ($(document).scrollTop() + window.innerHeight < $('#footer').offset().top)
$('#colizquierda').css('position', 'fixed');
if ($('#colderecha').offset().top + $('#colderecha').height() >= $('#footer').offset().top - 10)
$('#colderecha').css('position', 'absolute');
if($(document).scrollTop() + window.innerHeight < $('#footer').offset().top)
$('#colderecha').css('position', 'fixed');
}

Sticky Nav Sticks Too Late

I'm creating a page with sticky nav and it doesn't stick to the top immediately after the header image moves away (it's less than full page size). It only sticks after the size of one full page image has passed. The text inside the nav bar also moves after it sticks.
You can view the code here: https://jsfiddle.net/zinctan/7a436ojz/
This is my javascript:
$(function() {
// when we scroll down the window, do this:
$(window).scroll(function(){
//Getting the scroll percentage
var windowHeight = $(window).height();
var scrollHeight = $(window).scrollTop();
var scrollPercentage = (scrollHeight / windowHeight);
console.log(scrollPercentage);
// if we have scrolled past 200, add the alternate class to nav bar
if(scrollPercentage > 1) {
$('.navHighlighter').addClass('scrolling');
} else {
$('.navHighlighter').removeClass('scrolling');
}
});
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - 80
}, 1000);
return false;
}
}
}); // code courtesy of CSS-Tricks
// apply the class of nav-active to the current nav link
$('a').on('click', function(e) {
e.preventDefault();
$('li.nav-active').removeClass('nav-active');
$(this).parent('li').addClass('nav-active');
});
// get an array of 'href' of each a tag
var navLink = $('ul.navHighlighter a');
console.log(navLink);
var aArray = [];
for(var i = 0; i < navLink.length; i++) {
console.log(i);
var aChild = navLink[i];
var navArray = $(aChild).attr('href');
console.log(navArray);
aArray.push(navArray);
console.log(aArray);
var selector = aArray.join(" , ");
console.log(selector);
}
$(window).scroll(function(){
var scrollTop = $(window).scrollTop();
var tops = [];
$(selector).each(function(){
var top = $(this).position().top - 90;
if(scrollTop > top) {
var id = $(this).attr('id');
$('.nav-active').removeClass('nav-active');
$('a[href="#'+id+'"]').parent().addClass('nav-active');
}
tops.push(top);
});
});
});
Any help would be useful! Thank you :)
First of all it is a good practice to use:
$(document).ready(function(){
});
and then write your jQuery code in that function in order to assure that your script code will run after your html web page is fully loaded.
Now, I think that that should work:
$(document).ready(function() {
var topDist = $(".navHighlighter").position(); //save the position of your navbar, better use an id for that
$(document).scroll(function () {
var scroll = $(this).scrollTop();
if (scroll > topDist.top) { //when the scrolling reaches the very top of your navbar
$('.navHighlighter').addClass('scrolling');
} else {
$('.navHighlighter').removeClass('scrolling');
}
});
*rest of your code goes here*
});
Also, add:
top:0;
width: 100%;
to your .scrolling class in order to command your navbar to start just at the top of the user's window and to cover the whole width of the web page (position:fixed creates some issues on that so you have to set the width of your element, remember that).
I hope I helped and I got your demands right. Happy coding! :)

How to add a jQuery scrollTop offset?

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

Active anchor links not getting set properly on fixed nav on scroll/click

I'm adding and removing a class for active anchor link (color:red). The issue is the class is not being added consistently according to sections and I don't seem to figure this one out.
How can I modify my code as so anchor links get "highlited" when its respective section is on top of the page consistently?
Here is my code:
// for secondary nav
var topRange = 200, // measure from the top of the viewport to X pixels down
edgeMargin = 20, // margin above the top or margin from the end of the page
contentTop = [];
// Set up content an array of locations for secondary nav
$('.overlay-box').find('a').each(function(){
var href = $(this).attr('href');
var name = href.substr(href.lastIndexOf('#')+1);
contentTop.push( $('[name="' + name + '"]').offset().top );
});
// adjust secondary nav on scroll
$(window).scroll(function(){
var winTop = $(window).scrollTop(),
bodyHt = $(document).height(),
vpHt = $(window).height() + edgeMargin; // viewport height + margin
$.each( contentTop, function(i,loc){
if ( ( loc > winTop - edgeMargin && ( loc < winTop + topRange || ( winTop + vpHt ) >= bodyHt ) ) ){
$('.nav-bar li')
.removeClass('anchor-selected')
.eq(i).addClass('anchor-selected');
}
});
});
here is the site:
http://www.icontrol.com/what-we-do/platform-services/
I cant see exactly how you are going about doing this.
I have put together a jsfiddle to achieve what you are looking to do
Hope its what you need :-)
http://jsfiddle.net/66ZbB/
$(document).ready(function() {
$('a').click(function() {
$('a').removeClass('anchor-selected');
var obj = $(this);
$('html, body').animate({
scrollTop: obj.offset().top
}, 1000, function () {
obj.addClass('anchor-selected');
});
});
$(window).scroll(function() {
$('a').removeClass('anchor-selected');
//alert($(window).scrollTop() +":");
$('a').each(function() {
console.log($(this).offset.top);
if (($(window).scrollTop() <= ($(this).offset().top)) && ($(window).scrollTop() > ($(this).offset().top - 20))) {
$(this).addClass('anchor-selected');
}
});
});
});

Get the height of a div jquery

I am trying to make a navigation, that sets the "active" class to links whenever it scrolls a specified ammount of pixels. But there is a div on the page, that get's its size based on user interaction.
This is the code for setting the active class.
$(function() {
//caches a jQuery object containing the header element
var header = $(".active");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >=760) {
header.removeClass('active').addClass("active1");
}
else { header.removeClass('active1').addClass('active');}
});
var header1 = $("#work");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 759 && scroll < 780) {
header1.removeClass('#work').addClass("active");
} else {
header1.removeClass("active").addClass('#work');
}
});
var header2 = $("#about");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll > 779 && scroll < 1450) {
header2.removeClass('#about').addClass("active");
} else {
header2.removeClass("active").addClass('#about');
}
});
var header3 = $("#contact");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll > 1449) {
header3.removeClass('#contact').addClass("active");
} else {
header3.removeClass("active").addClass('#contact');
}
});
});
How do I get the height of a div which has it's class set as auto, and then apply it in the code above ?
EDIT: I tried the $('#ID').height(); but it gets the height when the website is loaded, and it doesn't work after any user interacts with the div.
In basically get the height of the DIV
$('#ID').height();
it returns height.
I guess this is what you are looking for
Sample DEMO
if($("#ID").offset().top < $(window).scrollTop() + $(window).outerHeight())
If you create a fiddle possibly can do the same for you
Hope this helps, Thank you

Categories