Scroll to left-most element on window resize - how? - javascript

I'm a bit of a jQuery newbie, only recently started.
I am using http://flesler.blogspot.com.au/2007/10/jqueryscrollto.html (Ariel Flesler's scrollTo plugin)
it's a horizontal scrolling website.
I'm trying to scroll to the element which is closest to the left side of the window when the window gets resized.
I can only seem to be able to get it to scroll to the first element in the array, so when I resize the window, no matter where the window is, the window scrolls to the first ".example" in the flow.
Update: I've made some progress, I've added a new variable to calculate how far has been scrolled. now i seem to need a way to find out what the lowest value of the loop is to use in my "if" statement as it seems to want to jump from one element to the next or none at all.
the "Uncaught TypeError: Cannot read property 'slice' of undefined was due to the value of the scrollTo being negative (you can't scroll below 0 as 0 is the beginning of your document) so to fix this i added the value of how much has been scrolled so far, and then added whatever value element_position had to calculate correctly.
Update 2: there was a problem with my mathematics, the question has been updated to reflect the solution. only problem now is that it's a fluid layout, so using fixed values like "70" in my if statement tend to break it after a certain point.
jQuery
$(document).ready(function(){
$(window).resize(function() {
$('.example').each(function(index) {
var example = $(this);
var scroll_position = $('#container').scrollLeft();
var element_position = example.offset().left;
if (element_position < 70 && position > -70) {
$('#container').scrollTo(scroll_position + element_position);
}
});
});
});
HTML
<div id="container">
<div class="example"></div>
<div class="example"></div>
<div class="example"></div>
<div class="example"></div>
<div class="example"></div>
<div class="example"></div>
</div>
I also recieve the following error
"Uncaught TypeError: Cannot read property 'slice' of undefined

try this one:
$(document).ready(function(){
$(window).resize(function() {
var scroll_position = $('#container').scrollLeft();
$('.example').each(function() {
var example = $(this);
var left = example.offset().left;
var right = left + example.width();
if (right > 0) {
$('#container').scrollTo(scroll_position + left);
return false;
}
});
});
});​
checks for the first element in the selected elements that has its right border in the viewport..

Related

Adding offset().top amount on scroll

I have a fixed piece of text and I'm trying to add a different class each time the text enters a div on scroll. I've got it working no problem. But if I add an offset amount to the fixed text e.g.
top: 400px
I need to counter this offset in the JS. But I can't seem to figure it out. I've tried using:
.offset().top 400);
But it's not working. Here's a code i'm currently using:
HTML
<p class="text">TEXT HERE</p>
<div class="section1"></div>
<div class="section2"></div>
<div class="section3"></div>
<div class="section4"></div>
JS
$(window).scroll(function (event) {
var scroll = $(window).scrollTop();
$('.text').toggleClass('blue',
scroll >= $('.section1').offset().top
);
$('.text').toggleClass('magenta',
scroll >= $('.section2').offset().top
);
$('.text').toggleClass('green',
scroll >= $('.section3').offset().top
);
$('.text').toggleClass('orange',
scroll >= $('.section4').offset().top
);
});
//trigger the scroll
$(window).scroll();//ensure if you're in current position when page is refreshed
The text needs to add class as soon as it enters the relevant div.
Here's a working fiddle: http://jsfiddle.net/6PrQW/334/
So you did most everything right, but I think where you went wrong is here: var scroll = $(window).scrollTop();
You don't want to calculate using the window offset, rather you want to use the offset of your sticky text. So instead use: var scroll = $('.text').offset().top;
Let me know if that helps.
edit,
and here is your fiddle with the edits.
Note that I edited your line for setting the blue class since you don't want to match the sticky offset against itself.
To find out when something is within your window, you've gotta use something like...
if($(elem).offset().top - $(window).scrollTop < $(window).height()){
//stuff
}
That should trigger as soon as elem is visible on the page! You can check it against $(window).height()/2, for example, if you want it to trigger in the center of the page instead. Hope this helps!

how to get the height of an element and then apply that value through css

I am trying to get the height of my navigation and apply it to a margin-top so I can offset my banner. My navigation is fixed so I'm trying to compensate for that so my banner isn't hidden underneath.
// Offset Banner to Height of Navigation
function bannerOffset() {
var bannerTop = $('.x-navbar').height();
$('#banner-carousel').css('margin-top', bannerTop);
}
This, I thought would do it, but it doesn't reflect anything at all in the front-end.
UPDATE
$(document).ready(function() {
var bannerTop = $('.x-navbar').outerHeight();
$('.x-main').css('margin-top', bannerTop);
$(window).scroll(function() {
var bannerTopScroll = $('.x-navbar.scroll').outerHeight();
if ($(document).scrollTop() > 1) {
$('.x-main').css('margin-top', bannerTopScroll);
}
});
});
So I thought I had this, but on load, the margin-top of .x-main is 245px. When I scroll it becomes 85px. I can see the numbers go down to that. The issue is when I scroll back up to the top the value doesn't go back to 245px. It's not very consistent, but I often get 144px. I should add that, and this is probably why, I have another function that changes the height of my .x-navbar when .scroll is added to it.
$(window).scroll(function() {
if ($(document).scrollTop() > 1) {
$('.x-navbar').addClass('scroll');
} else {
$('.x-navbar').removeClass('scroll');
}
});
So I am not sure how to make this all smooth and working properly. If I reload the page the .x-mainis back to 245px. When I scroll back to the top it's not calculating properly.
Your code works. Maybe you want to use $.outerHeight() instead, your selectors are wrong, or you're experiencing margin collapsing.
It's worth noting that $.height() returns an integer value, so in your $.css() line, you should change bannerTop to bannerTop + 'px' so that the CSS has a unit and not just a number... but it looks like jQuery is doing that automagically for me here. You might try it and see.
var bannerTop = $('.x-navbar').height();
$('#banner-carousel').css('margin-top', bannerTop);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="x-navbar">x-navbar<br>x-navbar<br>x-navbar<br>x-navbar<br>x-navbar<br>x-navbar<br>x-navbar<br>x-navbar<br></div>
<div id="banner-carousel">banner carousel</div>

Scroll Bouncing With Fixed Positioning

I have a fixed element that attaches on my page when you reach it in the scroll. This element can sometimes have content above it but not below it, meaning the page depth might not be deep enough to support this kind of behavior, because of this it prevents the user from reaching the bottom of the page and causes the page to bounce, presumably because it's removing the element from the scroll when it fixes, which causes the condition in the scroll event function to no longer be true. The gif shows the undesired effect when this happens.
Demonstrated here in this fiddle: https://jsfiddle.net/dcsjx625/8/
The pages are dynamic so removing the effect for a single page is not possible.
<body>
<div class="header">
<img src="http://placehold.it/600x401">
</div>
<div class="content-parent">
<div class="content">
<img src="http://placehold.it/600x400">
<img src="http://placehold.it/600x400">
<img src="http://placehold.it/600x400">
</div>
</div>
<div class="footer-content">
Footer
</div>
</body>
jQuery:
var $stickyChainOffset = $('.content').offset();
var $stickyChain = $('.content');
var $fixedWidth = $('.content').parent().width();
function checkScroll() {
if ($(window).scrollTop() > $stickyChainOffset.top - 100) {
$stickyChain.css('position', 'fixed').css('top', '100px').css('max-width', $fixedWidth);
} else {
$stickyChain.css('position', 'static').css('max-width', 'initial');
}
};
$(window).scroll(function() {
checkScroll();
});
/* Updates the $fixedWidth variable on resize */
$(window).resize(function() {
$fixedWidth = $('.content').parent().width();
$(window).scroll();
});
Ideally I want to prevent the sticking effect if the element is close enough to the bottom of the page that it might cause a problem.
I've tried calculating the page depth vs the element height in the checkScroll() function like so but even this isn't working. I feel like I'm right on the edge of solving this.:
function checkScroll() {
height = $stickyChain.height() + 100;
depth = $(document).height() - $stickyChainOffset.top;
if ($(window).scrollTop() > $stickyChainOffset.top - 100 && depth > height) {
$stickyChain.css('position', 'fixed').css('top', '100px').css('max-width', $fixedWidth);
} else {
$stickyChain.css('position', 'static').css('max-width', 'initial');
}
};
Any help would be greatly appreciated!
I gotta be honest, I understand your problem but I have no idea when and why you'd run into this exact behavior. That said, here's my workaround and some notes:
The height of your content needs to be 2x the height of fixed element in order to maintain the scrollbar. Otherwise, once the element is fixed, your document entirely loses the scrollbar.
I'm saving the original offset of fixed element to a variable that is used as a marker for future reset. However, I am also redefining the $stickyChainOffset in every scroll event, that you used to define only once. I'm doing this because it changes once fixed.
You can comment and uncomment the padding I saved in css to see how the page behaves in various cases.
If you have any other questions, let me know.
https://jsfiddle.net/1fke1j3d/1/

How to stick a div at the bottom of the page while scrolling after checkbox is checked

Usually I don't ask questions...I'm looking for a solution until I give up,
and this is the case here.
There are many similar questions to my but after a thorough search I found nothing.
So the question is:
After selecting a checkbox the div at the bottom of the page
shuold be sticky untill the user scrolling down to the original place where it was.
I have a great example from kickstarter web site :
If only I could know how they do it :)
If I was not clear enough I'd love to explain myself better.
Thanks in advance
After clicking on checkbox,
You can add these CSS lines to div
position:fixed;
bottom:0;
you want to add position: fixed and attach it to the bottom of the container when checked
html
<div class="wrapper">
<input type="checkbox" id="check"/>
<div id="foot"></div>
</div>
js
var check = document.getElementById('check');
var foot = document.getElementById('foot');
check.addEventListener('change', function () {
if (check.checked) {
foot.style.position = 'fixed';
foot.style.bottom = 0;
}
});
fiddle - http://jsfiddle.net/qak2ept6/
EDIT - http://jsfiddle.net/qak2ept6/1/ restore when unchecked
EDIT EDIT - http://jsfiddle.net/qak2ept6/3/ attach on scroll
when you check the check box. create div with position fixed and store the offset of the bottom edge of the window that would be normally your window height. Assign scroll event and keep checking if the scroll value is equal to the offset you have stored and when it reached just remove the fixed position from the div.
My guess (and if I was doing it) It'll be done by monitoring scroll position and applying a css style or not accordingly.
Something like
Inject it in invisible state in to the document
Note it's position (y coord)
Apply class to make it stick to the bottom of the window and show
On scroll, as soon as you get near the expected yCoord, remove the class and let it assume it's rightful place in the document
On further scroll (when you scroll away), re-apply class until you scroll back
HTH
If i have understood your question, I guess what you want is here
function sticky_relocate() {
var window_top = $(window).scrollTop();
var div_top = $('#sticky-anchor').offset().top
if (window_top > div_top) {
$('#sticky').addClass('stick');
} else {
$('#sticky').removeClass('stick');
}
}
$(function () {
$(window).scroll(sticky_relocate);
sticky_relocate();
});
If not, please explain us with more code and what exactly you need

Jquery change div based on another div's position

Let me start of by saying, I'm just now learning JS and Jquery, so my knowledge is very limited.
I've been looking around for 2 days now, and tried all sorts of combinations. But I just can't get this to work.
Below is an example of the layout
I'm looking for a way to trigger an event when div 1 is X px from the top of the screen. Or when div 1 collides with div 2.
What I'm trying to accomplish is to change the css of div 2 (the fixed menu) when div 1 is (in this case) 100px from the top of screen (browser window). Alternatively, when div1 passes div2 (I'm using responsive design, so the fixed height from top might become a problem on smaller screens right? Seeing as the header for example won't be there on a hand held.). So maybe collision detection is better here? Would really appreciate some thoughts and input on this matter.
Another issue is, div2 has to revert back to is previous css once div1 passes it (going back (beyond the 100px)).
This is what I have but it has no effect
$(document).ready(function() {
var content = $('#div1');
var top = $('#div2');
$(window).on('scroll', function() {
if(content.offset().top <= 100) {
top.css({'opacity': 0.8});
}else{
top.css({'opacity': 1});
}
});
});
I am not sure of the reason but $("#content").offset().top was giving a constant value on console. So I added window.scrollTOp() to check its distance from top, here is how it works,
$(document).ready(function() {
var top = $("#menu");
$(window).on('scroll', function(){
if(($('#content').offset().top - $(window).scrollTop()) <= 100){
top.css({'opacity': 0.4});
}else{
top.css({'opacity': 1});
}
});
});
And DEMO JSFIDDLE....

Categories