jQuery height() returning no value - javascript

I want to make an scrollable div that scrolls down when the user hovers another div. The content inside the scrollable div will change (it's gonna be only text) so I can't set up an absolute height value for that DIV, this is why div's height is 'auto'.
I have come into a solution that works when I set up an absolut height value on '.post-right' div's CSS, but it returns no value if div's height is 'auto' just I like I need it to be.
I've tried putting jQuery block of code on the (document).ready function as well, result is exactly the same.
Any ideas? Thank's in advance.
HTML CODE:
<div class="post-right-cont">
<div class="post-right">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut aliquam libero ut nisi consectetur pretium. Donec auctor auctor mauris, in tempor mauris blandit et. Aliquam nibh felis, tincidunt a auctor vel, feugiat at enim. Duis faucibus porta mi ut fringilla. Pellentesque eleifend erat a tellus aliquam sodales. Nullam lorem tellus, accumsan quis laoreet id, luctus et urna. Curabitur eleifend tellus non orci ullamcorper adipiscing. Integer est tellus, bibendum at ultricies a, viverra at orci. Curabitur porta tincidunt nunc, at placerat ipsum malesuada et. Vivamus et est purus, id suscipit tortor. Curabitur turpis metus, dapibus et consectetur non, tincidunt in est. Vestibulum nisl libero, sodales sit amet auctor eu, congue at velit. Vivamus et erat massa, nec viverra risus. Fusce iaculis dolor vel augue ornare accumsan.<br/><br/>
Quisque a metus arcu. Suspendisse hendrerit commodo justo in sagittis. Phasellus a scelerisque quam. Fusce lacinia lacinia justo. Duis id hendrerit enim. Sed eleifend eros et turpis rutrum consectetur. Maecenas pulvinar volutpat odio, non imperdiet augue pretium quis. Proin rutrum, est vitae auctor dapibus, diam dolor rutrum libero, sed feugiat metus turpis sed mauris. Sed eleifend dolor arcu. Cras laoreet nibh convallis magna congue sit amet consequat tortor porttitor. Duis et mauris non lorem consectetur luctus. Aliquam mollis sem sit amet tortor iaculis egestas. Duis tincidunt pellentesque leo, nec vulputate turpis dapibus sit amet. Aliquam rhoncus luctus orci, et aliquet eros porttitor in. Etiam arcu eros, viverra tristique tincidunt vel, facilisis et mauris.<br/><br/>
Morbi congue auctor luctus. Sed nisl dui, varius id ornare et, tincidunt sit amet enim. Aliquam egestas ultricies nisl, id condimentum erat fermentum quis. Morbi lectus nunc, aliquam volutpat egestas quis, iaculis a nulla. Pellentesque fermentum mauris at libero pulvinar viverra. Aliquam a ante orci, a luctus purus. Vivamus ut est ut mauris pulvinar mattis ac et magna. Aenean congue dictum lectus at suscipit. Suspendisse interdum, erat pulvinar gravida vulputate, mi mauris feugiat justo, at euismod augue sapien eu sapien. Praesent at quam purus. In hac habitasse platea dictumst. Fusce vel tellus a massa tempor volutpat a at magna. In eu enim odio. Quisque bibendum tortor est. Phasellus a scelerisque quam. Fusce lacinia lacinia justo. Duis id hendrerit enim. Sed eleifend eros et turpis rutrum consectetur. Maecenas pulvinar volutpat odio, non imperdiet augue pretium quis. Proin rutrum, est vitae auctor dapibus, diam dolor rutrum libero, sed feugiat metus turpis sed mauris. Sed eleifend dolor arcu.
</div>
<div class="scroll-down"></div>
<div class="scroll-up"></div>
</div>
CSS:
.post-right-cont {
width: 540px;
height: auto;
overflow: hidden;
position: relative;
}
.post-right {
position: absolute;
top: 0;
left: 20px;
height: auto;
width: 480px;
padding-top: 40px;
}
jQuery:
$(window).load(function() {
// SCROLL POST
// EDIT - post-right-cont height was set up before. I just past it here now.
var wHeight = $(window).height();
$('.post-right-cont').css('height', wHeight - 36);
if ($('div.post-right').height() > $('.post-right-cont').height()) {
$('div.scroll-down').hover(function() {animateContent('down');}, function() {
$('div.post-right').stop();
});
$('div.scroll-up').hover(function() {animateContent('up');}, function() {
$('div.post-right').stop();
});
}
function animateContent(direction) {
var containerHeight = $('.post-right-cont').height();
var textHeight = $('div.post-right').height();
var animationOffset = textHeight - containerHeight;
if (direction == "up") {
animationOffset = 0;
}
$('div.post-right').animate({"top" : -animationOffset + "px" }, 8500);
}
});

$('.post-right-cont').height() will return a value 0 because you have wrapped just one item inside, which have absolute positioning, so the absolute positioned element will not increase the size of .post-right-cont. So jQuery returns the correct value - 0. The height of .post-right will not increase the height of .post-right-cont because absolute positioned elements do not increase the height or width of their wrapping tag.

Related

How to get the height of an element without its CSS?

My element has a CSS class that defines what the height of it should be.
.very-long-container {
height: 50px;
}
<div class="very-long-container">...</div>
I want to know the original height of that element, so not what is defined with CSS.
Well, my way of getting the height is to reset the CSS first, get the original height and then set the height with CSS again. Like this:
document.querySelector('.very-long-container').style.height = 'inherit';
console.log(document.querySelector('.very-long-container').offsetHeight);
document.querySelector('.very-long-container').style.height = '50px';
Since this is not the best practice, I am sure that there are better answers.
The container is 50px and will always be that if you tell it. When you remove the 50px from the CSS it will take the height of the children inside of it.
So one way of know what the actual height would be whenever there is no fixed height set is to either have another container inside of the container or to sum the height of all children inside of the container.
The former is the easiest to work out. If a child container does not have a fixed height, it will automatically take the height of the children inside of it, despite the outer container having a fixed height.
The example below uses the aforementioned technique. Reading the offsetHeight of the inner container. As a bonus it uses a ResizeObserver to update the height whenever the size of the inner container changes.
const innerContainer = document.querySelector('.inner-container');
let height = innerContainer.offsetHeight;
const resizeObserver = new ResizeObserver(entries => {
for (const { target } of entries) {
height = target.offsetHeight;
console.log(height);
}
});
resizeObserver.observe(innerContainer);
.very-long-container {
height: 50px;
overflow: hidden;
}
<div class="very-long-container">
<div class="inner-container">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam congue efficitur purus vel posuere. Nam eget tincidunt dolor, eu tempor neque. Aliquam ac ex urna. Ut scelerisque urna purus, tincidunt bibendum massa accumsan id. Mauris vitae cursus mi.
Phasellus imperdiet vel metus et ornare. Donec nulla justo, convallis sed lacus at, dapibus rhoncus neque. Cras velit erat, lacinia eu lectus lobortis, rhoncus congue ex. Curabitur lacus diam, dignissim at tortor ac, suscipit venenatis tortor. Fusce
tempus consectetur dui, vel placerat purus luctus nec. Morbi elementum, mi lacinia rhoncus vehicula, dolor dolor iaculis augue, id feugiat arcu tortor sed lectus. Quisque lacus justo, luctus sit amet finibus quis, pretium sed ex.
</p>
<p>
Morbi luctus neque non nunc placerat varius. Sed cursus scelerisque mi id interdum. Sed sodales orci ut laoreet imperdiet. Duis pretium erat ut libero consectetur ultrices. Aenean suscipit ultricies diam at pretium. Fusce pharetra lectus at lectus ornare,
sit amet lobortis libero lacinia. Quisque odio orci, ornare sed molestie non, fermentum at enim. Nam ut tortor enim. Nulla facilisi. Maecenas vehicula vitae felis ut mollis. Nam varius elementum felis, condimentum hendrerit velit elementum eu. Praesent
laoreet, turpis vel condimentum auctor, nisi erat viverra purus, sed gravida odio nulla nec urna.
</p>
<p>
Morbi sed enim ligula. Fusce vitae feugiat nunc. Sed vel velit orci. Nunc ut euismod ipsum. Cras sed velit nec lectus scelerisque sagittis. Fusce non nunc leo. Donec viverra eu felis sed molestie. Proin ut molestie libero, ut ultricies purus. Nullam dapibus
felis non vestibulum aliquam. Mauris quam mi, dictum eu nisi vitae, malesuada ultricies turpis. Donec vitae dolor leo. Nulla at dui eget eros molestie congue. Etiam imperdiet lobortis feugiat.
</p>
<p>
Maecenas enim magna, convallis vitae scelerisque at, lobortis vitae elit. Cras interdum ipsum non purus feugiat rhoncus. Fusce eu elit porttitor, aliquet libero at, dapibus massa. Suspendisse dignissim varius mauris, sed ullamcorper mauris interdum quis.
Proin viverra purus massa, in finibus magna faucibus ut. Nulla malesuada ipsum vel maximus vestibulum. Vestibulum molestie in dui fringilla interdum. Donec dignissim sapien nisl. Suspendisse aliquam elit turpis, at euismod mauris consectetur vel.
</p>
<p>
Suspendisse fermentum urna a arcu dignissim tincidunt. Nulla pellentesque orci vitae vulputate rutrum. Vestibulum interdum faucibus lectus vel vehicula. Suspendisse egestas dolor sit amet justo vehicula sodales. Integer fringilla eget erat id rhoncus.
Aenean luctus purus ut libero volutpat, viverra lobortis dui maximus. Integer sit amet aliquet nulla. In suscipit id orci sed tincidunt. Suspendisse pharetra suscipit tempus. Cras mattis a nibh eu porttitor. Donec nec iaculis metus. Pellentesque
molestie diam eu eleifend cursus. Suspendisse tincidunt, lorem quis pulvinar viverra, metus felis imperdiet nisi, ut dignissim velit urna nec odio. Quisque pulvinar turpis non ipsum mattis, a iaculis ipsum pellentesque. Vestibulum finibus sed sapien
quis faucibus. Vivamus tristique, neque id finibus ultrices, sapien elit consequat odio, placerat commodo magna odio id velit.
</p>
</div>
</div>

How to call a function based on element position?

I'm very new to Javascript. I'm trying to make a style change based on an element's position on the screen, but I'm pretty clueless as to how to make it work.
What I'm trying to do is make the background of an element become fixed once the element has reached the top of the page (and return to being unset when you scroll back up). So far I ended up with this code but as you can tell it triggers only when you click it. My question being which event should I use to make it go into action once the user has simply scrolled up to the point I intended?
const page2 = document.getElementById("about");
page2.addEventListener("click", bgFixer);
function bgFixer() {
rect = this.getBoundingClientRect();
if (rect.top <= 0) {
var style = document.createElement('style');
document.head.appendChild(style);
style.sheet.insertRule('.page-2{background-attachment: fixed}')
}
}
Thanks in advance! Just a reminder that I'm really new so the more detailed the explanations are the better.
You can test the distance of the scroll by checking scrollTop of your containing element.
If the distance between the top of your "sticky" element and the scrollTop is 0 or less, fix the "sticky" element in place by adding a class with position: fixed; top: 0px;
Since the above changes the position of the "sticky" element, we want to store the original top distance so we know that, when the distance of scrollTop is less than that of the original top distance, we remove the class.
let el = document.querySelector.bind(document),
c = el("#test"),
t = el("#toTop");
c.addEventListener("scroll", function() {
// get inner top distance
let ttop = t.getBoundingClientRect().top;
// get container scroll distance
let ctop = c.scrollTop;
// if the initial top distance isn't set, set it
if (!this.init) this.init = ttop;
// if the inner top is less than or equal to 0 ( no distance )
// and the container scroll is greater than the initial top distance
if (ttop <= 0 && ctop >= this.init) {
// make fixed
t.classList.add("stuck")
} else {
// remove fixed class
t.classList.remove("stuck");
}
});
let el = document.querySelector.bind(document),
c = el("#test"),
t = el("#toTop");
c.addEventListener("scroll", function() {
// get inner top distance
let ttop = t.getBoundingClientRect().top;
// get container scroll distance
let ctop = c.scrollTop;
// if the initial top distance isn't set, set it
if (!this.init) this.init = ttop;
// if the inner top is less than or equal to 0 ( no distance )
// and the container scroll is greater than the initial top distance
if (ttop <= 0 && ctop >= this.init) {
// make fixed
t.classList.add("stuck")
} else {
// remove fixed class
t.classList.remove("stuck");
}
});
body,
html {
height: 100%;
box-sizing: border-box;
margin: 0;
}
#test {
height: 50%;
overflow-y: scroll;
box-sizing: border-box;
}
#toTop::before {
position: absolute;
content: "";
left: 0;
top: 0;
width: 100%;
height: 100%;
box-shadow: 0 -1px red;
}
#toTop {
position: relative;
background: black;
color: white;
top: 300px;
height: auto;
width: 100%;
padding: 0;
margin: 0;
}
#toTop.stuck {
position: fixed;
top: 0px;
}
#after {
height: 1200px;
}
<div id="test">
<div id="toTop">test</div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Proin sagittis nisl rhoncus mattis rhoncus urna neque. Suspendisse ultrices gravida dictum fusce ut placerat orci. Neque volutpat
ac tincidunt vitae semper. Ac turpis egestas integer eget aliquet. Consectetur adipiscing elit duis tristique sollicitudin. Eget velit aliquet sagittis id consectetur purus ut faucibus pulvinar. Id consectetur purus ut faucibus pulvinar elementum
integer. Aliquet enim tortor at auctor urna nunc id. In fermentum et sollicitudin ac orci phasellus egestas tellus. Risus nullam eget felis eget.</p>
<p>
Mauris commodo quis imperdiet massa tincidunt nunc pulvinar sapien. Orci dapibus ultrices in iaculis nunc sed augue lacus. Sit amet venenatis urna cursus. Est velit egestas dui id ornare arcu odio ut. Consequat mauris nunc congue nisi vitae suscipit tellus
mauris a. Ipsum dolor sit amet consectetur adipiscing elit. Dolor purus non enim praesent elementum facilisis. Pharetra pharetra massa massa ultricies mi quis hendrerit dolor magna. Quam vulputate dignissim suspendisse in. Elementum pulvinar etiam
non quam lacus suspendisse. Sed augue lacus viverra vitae congue eu consequat ac felis. Egestas maecenas pharetra convallis posuere morbi leo urna molestie.
</p>
<p>
Sed libero enim sed faucibus. Malesuada fames ac turpis egestas integer eget aliquet nibh praesent. Diam vel quam elementum pulvinar etiam non. Molestie ac feugiat sed lectus vestibulum mattis. Quisque sagittis purus sit amet volutpat. Ac turpis egestas
integer eget aliquet nibh praesent tristique magna. Integer feugiat scelerisque varius morbi enim nunc faucibus a. Faucibus a pellentesque sit amet porttitor eget. Massa massa ultricies mi quis hendrerit dolor. Metus vulputate eu scelerisque felis
imperdiet proin fermentum. Bibendum neque egestas congue quisque egestas diam in. Duis at consectetur lorem donec massa. Eu consequat ac felis donec et. In tellus integer feugiat scelerisque varius morbi enim. Nulla facilisi morbi tempus iaculis urna
id. Mauris commodo quis imperdiet massa tincidunt nunc. Egestas purus viverra accumsan in. Malesuada proin libero nunc consequat interdum varius. Pulvinar elementum integer enim neque volutpat ac tincidunt.
</p>
<p>
Laoreet id donec ultrices tincidunt arcu non sodales. Tempor id eu nisl nunc mi ipsum. Urna molestie at elementum eu facilisis sed odio. Mauris pharetra et ultrices neque ornare aenean. Placerat vestibulum lectus mauris ultrices eros in. Feugiat nibh
sed pulvinar proin gravida hendrerit. Nisl suscipit adipiscing bibendum est. Pretium nibh ipsum consequat nisl vel pretium. Sed egestas egestas fringilla phasellus faucibus scelerisque eleifend donec. Dolor morbi non arcu risus. Nam aliquam sem et
tortor consequat id porta nibh. Sagittis nisl rhoncus mattis rhoncus.
</p>
<p>
Tellus molestie nunc non blandit massa enim nec dui. A iaculis at erat pellentesque. Nibh cras pulvinar mattis nunc. Nunc consequat interdum varius sit. Tortor at risus viverra adipiscing at in. Sed faucibus turpis in eu. Nunc faucibus a pellentesque
sit. Dignissim enim sit amet venenatis urna cursus eget nunc scelerisque. Aliquam ultrices sagittis orci a. Sagittis eu volutpat odio facilisis mauris sit. Risus at ultrices mi tempus. Libero volutpat sed cras ornare. Risus ultricies tristique nulla
aliquet enim tortor. Augue lacus viverra vitae congue. Sit amet mattis vulputate enim nulla aliquet porttitor. Risus in hendrerit gravida rutrum.
</p>
<p>
Mauris commodo quis imperdiet massa tincidunt nunc pulvinar sapien. Orci dapibus ultrices in iaculis nunc sed augue lacus. Sit amet venenatis urna cursus. Est velit egestas dui id ornare arcu odio ut. Consequat mauris nunc congue nisi vitae suscipit tellus
mauris a. Ipsum dolor sit amet consectetur adipiscing elit. Dolor purus non enim praesent elementum facilisis. Pharetra pharetra massa massa ultricies mi quis hendrerit dolor magna. Quam vulputate dignissim suspendisse in. Elementum pulvinar etiam
non quam lacus suspendisse. Sed augue lacus viverra vitae congue eu consequat ac felis. Egestas maecenas pharetra convallis posuere morbi leo urna molestie.
</p>
<p>
Sed libero enim sed faucibus. Malesuada fames ac turpis egestas integer eget aliquet nibh praesent. Diam vel quam elementum pulvinar etiam non. Molestie ac feugiat sed lectus vestibulum mattis. Quisque sagittis purus sit amet volutpat. Ac turpis egestas
integer eget aliquet nibh praesent tristique magna. Integer feugiat scelerisque varius morbi enim nunc faucibus a. Faucibus a pellentesque sit amet porttitor eget. Massa massa ultricies mi quis hendrerit dolor. Metus vulputate eu scelerisque felis
imperdiet proin fermentum. Bibendum neque egestas congue quisque egestas diam in. Duis at consectetur lorem donec massa. Eu consequat ac felis donec et. In tellus integer feugiat scelerisque varius morbi enim. Nulla facilisi morbi tempus iaculis urna
id. Mauris commodo quis imperdiet massa tincidunt nunc. Egestas purus viverra accumsan in. Malesuada proin libero nunc consequat interdum varius. Pulvinar elementum integer enim neque volutpat ac tincidunt.
</p>
<p>
Laoreet id donec ultrices tincidunt arcu non sodales. Tempor id eu nisl nunc mi ipsum. Urna molestie at elementum eu facilisis sed odio. Mauris pharetra et ultrices neque ornare aenean. Placerat vestibulum lectus mauris ultrices eros in. Feugiat nibh
sed pulvinar proin gravida hendrerit. Nisl suscipit adipiscing bibendum est. Pretium nibh ipsum consequat nisl vel pretium. Sed egestas egestas fringilla phasellus faucibus scelerisque eleifend donec. Dolor morbi non arcu risus. Nam aliquam sem et
tortor consequat id porta nibh. Sagittis nisl rhoncus mattis rhoncus.
</p>
<p>
Tellus molestie nunc non blandit massa enim nec dui. A iaculis at erat pellentesque. Nibh cras pulvinar mattis nunc. Nunc consequat interdum varius sit. Tortor at risus viverra adipiscing at in. Sed faucibus turpis in eu. Nunc faucibus a pellentesque
sit. Dignissim enim sit amet venenatis urna cursus eget nunc scelerisque. Aliquam ultrices sagittis orci a. Sagittis eu volutpat odio facilisis mauris sit. Risus at ultrices mi tempus. Libero volutpat sed cras ornare. Risus ultricies tristique nulla
aliquet enim tortor. Augue lacus viverra vitae congue. Sit amet mattis vulputate enim nulla aliquet porttitor. Risus in hendrerit gravida rutrum.
</p>
</div>
This can be done very easily now with position: sticky; it will change between fixed and static when it is at top: 0; defined only in CSS.
Learn more about sticky positioning: https://www.w3schools.com/howto/howto_css_sticky_element.asp
.top {
position: sticky;
top: 0;
background: red;
}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce quis feugiat lacus. Etiam mollis odio ipsum, et lobortis dolor fermentum gravida. Praesent volutpat metus quis venenatis venenatis. Sed semper pharetra nibh. In hac habitasse platea dictumst. Duis egestas felis ac maximus iaculis. Nulla quis metus condimentum, porta mi sed, convallis risus. Nulla vehicula lorem elit, eu pulvinar velit pretium quis. Maecenas vitae pulvinar massa. Morbi congue erat vitae pharetra faucibus.</p>
<p class="top">top</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce quis feugiat lacus. Etiam mollis odio ipsum, et lobortis dolor fermentum gravida. Praesent volutpat metus quis venenatis venenatis. Sed semper pharetra nibh. In hac habitasse platea dictumst. Duis egestas felis ac maximus iaculis. Nulla quis metus condimentum, porta mi sed, convallis risus. Nulla vehicula lorem elit, eu pulvinar velit pretium quis. Maecenas vitae pulvinar massa. Morbi congue erat vitae pharetra faucibus.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce quis feugiat lacus. Etiam mollis odio ipsum, et lobortis dolor fermentum gravida. Praesent volutpat metus quis venenatis venenatis. Sed semper pharetra nibh. In hac habitasse platea dictumst. Duis egestas felis ac maximus iaculis. Nulla quis metus condimentum, porta mi sed, convallis risus. Nulla vehicula lorem elit, eu pulvinar velit pretium quis. Maecenas vitae pulvinar massa. Morbi congue erat vitae pharetra faucibus.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce quis feugiat lacus. Etiam mollis odio ipsum, et lobortis dolor fermentum gravida. Praesent volutpat metus quis venenatis venenatis. Sed semper pharetra nibh. In hac habitasse platea dictumst. Duis egestas felis ac maximus iaculis. Nulla quis metus condimentum, porta mi sed, convallis risus. Nulla vehicula lorem elit, eu pulvinar velit pretium quis. Maecenas vitae pulvinar massa. Morbi congue erat vitae pharetra faucibus.</p>

Can I animate this image diagonally across the screen on scroll and slower than the window?

I am trying to make this image animate across the screen from the top left to the bottom right as I scroll down the page. I would really love to have the image scroll slower than the page so that it will be on screen the whole time. I looked into paralax but am unsure if this is the best solution. Bonus points if there was a way to make it start smaller, then get bigger as it scrolls down, giving it the appearance of coming closer from far away.
Here is a link to the page as as it's working now for reference:
HTML
<section class="astronaut">
<img src="assets/Images/astronaut_PNG69.png" alt="astronaut"
class="astronautImage">
</section>`
JavaScript
let current = $(window).scrollTop();
const total = $(window).height() - current;
const ele = $(".astronautImage");
const currPosition = ele.position().left;
const trackLength = 250;
$(window).scroll(function (event) {
current = $(window).scrollTop();
console.log({ total: total, current: current });
console.log(current / total * 100);
const newPosition = trackLength * (current / total)
ele.css({ left: currPosition + newPosition * (8) + 'px' });
});
Using css transform looks more easy and will render smooth animation of what you are trying to accomplish. This is an idea to get you started, just apply some percentages to scale and translate to make it consistent
var measure = {
totalY: document.body.scrollHeight,
totalX: document.body.scrollWidth,
screenY: screen.height,
screenX: screen.width,
}
$(document).on('scroll', function() {
const posY = $(this).scrollTop();
const pos = {
x: measure.screenX / measure.totalY * posY + 'px',
y: posY + (measure.screenY / measure.totalY * posY) + 'px',
};
$('img').css('transform', `translate(${pos.x},${pos.y}) scale(${(1 + posY / measure.screenY)})`)
});
<div style="margin-bottom: 5000px;">
<img src="https://jonalden.github.io/JonAldenPortfolio/assets/Images/astronaut_PNG69.png" style="transform: translate(0, 0) scale(1);width: 100px;" />
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
For moving an image diagonally you need to depend on y position as you are only scrolling for y in your page.
Updated fiddle : https://jsfiddle.net/m2uewboh/1/
To position the moving element in the background without having it scroll, I would use a position: fixed element as a frame (called background below) and then position the astronaut (called rocket below) relative to it.
All that's left to do is adjust the margin properties when the user scrolls. You might also want to add a transition to make it more smooth.
To make it get bigger, you can do that same thing with either the width/ height properties or with transform: scale(...).
#background {
position: fixed;
z-index: -1;
top: 0;
left: 0;
right: 0;
bottom: 0;
border: 1px solid red;
}
#rocket {
height: 50px;
width: 50px;
background: rgb(150, 200, 210);
margin-top: 10%;
margin-left: 10%;
}
<div id="background">
<div id="rocket"></div>
</div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Eget mi proin sed libero enim sed. Faucibus purus in massa tempor nec feugiat nisl. Amet tellus cras adipiscing enim. Nulla pellentesque dignissim enim sit. Id velit ut tortor pretium viverra suspendisse potenti nullam ac. Sit amet purus gravida quis blandit turpis cursus in. Aliquam etiam erat velit scelerisque in dictum non consectetur a. Vitae auctor eu augue ut. Dignissim convallis aenean et tortor at risus. Nec sagittis aliquam malesuada bibendum arcu vitae. Dictumst vestibulum rhoncus est pellentesque elit ullamcorper dignissim. Tempor orci dapibus ultrices in iaculis nunc sed. Donec et odio pellentesque diam volutpat commodo sed. Dui accumsan sit amet nulla facilisi morbi tempus iaculis. Sit amet tellus cras adipiscing enim eu turpis egestas pretium. Eget nunc lobortis mattis aliquam faucibus purus in massa. Faucibus nisl tincidunt eget nullam.
Nunc sed velit dignissim sodales ut eu sem. Turpis tincidunt id aliquet risus feugiat in ante. Purus sit amet luctus venenatis lectus magna fringilla urna. A cras semper auctor neque. Duis at tellus at urna condimentum mattis pellentesque. Ut sem viverra aliquet eget sit amet tellus. Phasellus egestas tellus rutrum tellus pellentesque eu tincidunt. Tempor id eu nisl nunc. Pulvinar proin gravida hendrerit lectus. Integer eget aliquet nibh praesent tristique. Tincidunt vitae semper quis lectus. Massa massa ultricies mi quis hendrerit dolor magna eget. Nunc vel risus commodo viverra maecenas accumsan lacus. Elementum eu facilisis sed odio morbi quis commodo. Viverra tellus in hac habitasse platea.<br>
Nunc sed velit dignissim sodales ut eu sem. Turpis tincidunt id aliquet risus feugiat in ante. Purus sit amet luctus venenatis lectus magna fringilla urna. A cras semper auctor neque. Duis at tellus at urna condimentum mattis pellentesque. Ut sem viverra aliquet eget sit amet tellus. Phasellus egestas tellus rutrum tellus pellentesque eu tincidunt. Tempor id eu nisl nunc. Pulvinar proin gravida hendrerit lectus. Integer eget aliquet nibh praesent tristique. Tincidunt vitae semper quis lectus. Massa massa ultricies mi quis hendrerit dolor magna eget. Nunc vel risus commodo viverra maecenas accumsan lacus. Elementum eu facilisis sed odio morbi quis commodo. Viverra tellus in hac habitasse platea.<br>
Nunc sed velit dignissim sodales ut eu sem. Turpis tincidunt id aliquet risus feugiat in ante. Purus sit amet luctus venenatis lectus magna fringilla urna. A cras semper auctor neque. Duis at tellus at urna condimentum mattis pellentesque. Ut sem viverra aliquet eget sit amet tellus. Phasellus egestas tellus rutrum tellus pellentesque eu tincidunt. Tempor id eu nisl nunc. Pulvinar proin gravida hendrerit lectus. Integer eget aliquet nibh praesent tristique. Tincidunt vitae semper quis lectus. Massa massa ultricies mi quis hendrerit dolor magna eget. Nunc vel risus commodo viverra maecenas accumsan lacus. Elementum eu facilisis sed odio morbi quis commodo. Viverra tellus in hac habitasse platea.<br>
Nunc sed velit dignissim sodales ut eu sem. Turpis tincidunt id aliquet risus feugiat in ante. Purus sit amet luctus venenatis lectus magna fringilla urna. A cras semper auctor neque. Duis at tellus at urna condimentum mattis pellentesque. Ut sem viverra aliquet eget sit amet tellus. Phasellus egestas tellus rutrum tellus pellentesque eu tincidunt. Tempor id eu nisl nunc. Pulvinar proin gravida hendrerit lectus. Integer eget aliquet nibh praesent tristique. Tincidunt vitae semper quis lectus. Massa massa ultricies mi quis hendrerit dolor magna eget. Nunc vel risus commodo viverra maecenas accumsan lacus. Elementum eu facilisis sed odio morbi quis commodo. Viverra tellus in hac habitasse platea.

scroll event listener + position: sticky element that changes height causes jittery infinite scroll

I have an element at the top of the screen with position:sticky; and a JS scroll eventlistener to add a stuck class when the element is stuck (scroll Y is bigger than 0).
This stuck makes an element (that has CSS transition) inside the sticky element to reduce in height.
When you scroll very slowly, this change in height makes the scrollY jump back to zero and removes the stuck class, and this creates a jolty scrolling loop which is infinite until you scroll faster and outscroll the issue.
How can I make this smooth when using position: sticky, you can see it live here:
https://jsfiddle.net/27rzba5v/
This is happening because you're changing the element's height, which is affecting the box model and thus the dimensions of your document. A simple fix would be to instead use a transform on .wrap instead of transitioning its height. It's better to animate transforms and opacity as it can be handled by the GPU rather than by making the browser repaint.
var lastScrollY = 0;
var ticking = false;
window.addEventListener('scroll', function(e) {
lastScrollY = window.scrollY;
if ( ! ticking ) {
window.requestAnimationFrame(function() {
console.log( lastScrollY );
if ( lastScrollY > 0 ) {
document.body.classList.add('stuck');
} else {
document.body.classList.remove('stuck');
}
ticking = false;
});
ticking = true;
}
} );
body {
margin: 0;
}
.wrap {
background: #666;
text-align: center;
position: sticky;
top: 0;
transition: 0.5s; /* Move transition here */
transform-origin: top left; /* Make sure transition happens from the top left */
}
.block {
width: 80px;
height: 80px;
background: red;
display: block;
}
.stuck .wrap { /* Transform wrap instead of block */
transform: scaleY(.5); /* Change scale instead of height */
}
<div class="wrap">
<span class="block"></span>
</div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque ac lorem a metus tincidunt eleifend id in odio. Nam malesuada hendrerit tristique. Pellentesque id ornare elit, ac lobortis metus. Sed iaculis et nisi et consectetur. Proin pellentesque metus mi, quis fringilla mauris pulvinar et. Vivamus pharetra elit ligula, eu consectetur magna consequat nec. Donec sed enim sit amet augue malesuada varius id a libero. Nullam nec ante id justo elementum congue quis in purus. Integer finibus cursus volutpat. Donec non laoreet ipsum.
Maecenas id venenatis velit, eu feugiat dolor. Vestibulum malesuada erat ut turpis mattis vehicula. Vestibulum sem leo, cursus quis lacinia eu, tincidunt eu velit. Nulla odio elit, tristique vel bibendum vitae, placerat nec eros. Proin auctor id leo sed rutrum. Proin convallis erat sit amet neque aliquam vestibulum. Ut sodales vel nisl eu imperdiet.
Donec a porttitor dui, vitae ullamcorper nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nullam non elit eu elit blandit hendrerit id ut eros. Duis sagittis elementum ligula eu venenatis. Aenean nunc mauris, dignissim ut venenatis ac, pharetra eget magna. Curabitur elementum enim sed pharetra rhoncus. Praesent sodales at ex at consectetur. Curabitur sed dictum mi, ut eleifend arcu. Nam feugiat risus quis congue porttitor. Maecenas vehicula lorem ultrices ante sollicitudin, placerat sollicitudin dolor fermentum. Aliquam arcu turpis, faucibus vel placerat a, molestie vel lectus. Sed condimentum euismod tincidunt. Mauris odio tortor, luctus id eleifend vitae, aliquet ut libero. Vestibulum vitae placerat turpis. Duis nec facilisis eros. Morbi ipsum arcu, tempus ac massa nec, mollis aliquet lacus.
Phasellus maximus eros quis massa maximus, et mattis tellus cursus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras id lacus interdum, cursus diam ut, posuere purus. Duis non vestibulum nulla, vitae egestas elit. Phasellus venenatis libero in nunc lobortis tempor in vel orci. Praesent varius lacus eleifend, pretium lectus ut, pulvinar arcu. Nunc ornare dolor velit, id pulvinar urna semper eget. Aenean finibus dui vitae dolor ullamcorper finibus. Cras consequat viverra tellus, a accumsan sem viverra sed. Nulla felis tortor, laoreet non tincidunt elementum, tempus ac risus. Sed nibh nisl, ultrices vel iaculis in, fringilla at ipsum. Curabitur metus ligula, tincidunt non arcu eget, ultricies pellentesque ligula. Duis id est posuere, molestie urna non, gravida tortor. Praesent lacinia erat ac diam sagittis, quis faucibus nunc blandit.
Fusce aliquet tincidunt turpis, ut consequat metus consectetur at. Nunc volutpat semper enim, ut finibus orci luctus in. Mauris pharetra consectetur arcu sed pulvinar. Sed cursus fermentum velit, mattis varius ante commodo ac. Fusce erat mauris, sagittis quis eros vitae, consectetur venenatis nibh. Fusce porttitor tortor lectus, at efficitur diam dictum et. Quisque et suscipit sem. Mauris vulputate orci tellus, non efficitur eros blandit ut. Donec eget hendrerit elit.
If you must transition the element's height then you could offset the effects of the dimensions changing by using a container as a buffer.
var lastScrollY = 0;
var ticking = false;
window.addEventListener('scroll', function(e) {
lastScrollY = window.scrollY;
if ( ! ticking ) {
window.requestAnimationFrame(function() {
console.log( lastScrollY );
if ( lastScrollY > 0 ) {
document.body.classList.add('stuck');
} else {
document.body.classList.remove('stuck');
}
ticking = false;
});
ticking = true;
}
} );
body {
margin: 0;
}
.wrapoffset { /* Make this element sticky instead */
height: 80px;
position: sticky;
top: 0;
width: 100%;
}
.wrap {
background: #666;
text-align: center;
width: 100%;
}
.block {
height: 80px;
width: 80px;
background: red;
display: block;
transition: 0.5s;
}
.stuck .block {
height: 40px;
}
<div class="wrapoffset"> <!-- new element -->
<div class="wrap">
<span class="block"></span>
</div>
</div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque ac lorem a metus tincidunt eleifend id in odio. Nam malesuada hendrerit tristique. Pellentesque id ornare elit, ac lobortis metus. Sed iaculis et nisi et consectetur. Proin pellentesque metus mi, quis fringilla mauris pulvinar et. Vivamus pharetra elit ligula, eu consectetur magna consequat nec. Donec sed enim sit amet augue malesuada varius id a libero. Nullam nec ante id justo elementum congue quis in purus. Integer finibus cursus volutpat. Donec non laoreet ipsum.
Maecenas id venenatis velit, eu feugiat dolor. Vestibulum malesuada erat ut turpis mattis vehicula. Vestibulum sem leo, cursus quis lacinia eu, tincidunt eu velit. Nulla odio elit, tristique vel bibendum vitae, placerat nec eros. Proin auctor id leo sed rutrum. Proin convallis erat sit amet neque aliquam vestibulum. Ut sodales vel nisl eu imperdiet.
Donec a porttitor dui, vitae ullamcorper nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nullam non elit eu elit blandit hendrerit id ut eros. Duis sagittis elementum ligula eu venenatis. Aenean nunc mauris, dignissim ut venenatis ac, pharetra eget magna. Curabitur elementum enim sed pharetra rhoncus. Praesent sodales at ex at consectetur. Curabitur sed dictum mi, ut eleifend arcu. Nam feugiat risus quis congue porttitor. Maecenas vehicula lorem ultrices ante sollicitudin, placerat sollicitudin dolor fermentum. Aliquam arcu turpis, faucibus vel placerat a, molestie vel lectus. Sed condimentum euismod tincidunt. Mauris odio tortor, luctus id eleifend vitae, aliquet ut libero. Vestibulum vitae placerat turpis. Duis nec facilisis eros. Morbi ipsum arcu, tempus ac massa nec, mollis aliquet lacus.
Phasellus maximus eros quis massa maximus, et mattis tellus cursus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras id lacus interdum, cursus diam ut, posuere purus. Duis non vestibulum nulla, vitae egestas elit. Phasellus venenatis libero in nunc lobortis tempor in vel orci. Praesent varius lacus eleifend, pretium lectus ut, pulvinar arcu. Nunc ornare dolor velit, id pulvinar urna semper eget. Aenean finibus dui vitae dolor ullamcorper finibus. Cras consequat viverra tellus, a accumsan sem viverra sed. Nulla felis tortor, laoreet non tincidunt elementum, tempus ac risus. Sed nibh nisl, ultrices vel iaculis in, fringilla at ipsum. Curabitur metus ligula, tincidunt non arcu eget, ultricies pellentesque ligula. Duis id est posuere, molestie urna non, gravida tortor. Praesent lacinia erat ac diam sagittis, quis faucibus nunc blandit.
Fusce aliquet tincidunt turpis, ut consequat metus consectetur at. Nunc volutpat semper enim, ut finibus orci luctus in. Mauris pharetra consectetur arcu sed pulvinar. Sed cursus fermentum velit, mattis varius ante commodo ac. Fusce erat mauris, sagittis quis eros vitae, consectetur venenatis nibh. Fusce porttitor tortor lectus, at efficitur diam dictum et. Quisque et suscipit sem. Mauris vulputate orci tellus, non efficitur eros blandit ut. Donec eget hendrerit elit.
If you want to optimize the performance even more you can look into using IntersectionObserver with a polyfill instead of listening for events on scroll.

Hide the content under transparent fixed navbar while scrolling down

the problem:
I have transparent fixed navbar with some gap (margin-top) and below content, which is located under the navbar while scrolling down globally. The problem is that navbar is transparent and the background of the page is a dynamic slideshow of different images so I can't use z-index and hide it by changing background color or put image same as background..
In conclusion:
Transparent fixed navbar with gap
Dynamic images background
It has to be global scrolling (can't use scrolling for div content)
I'am using bootstrap 3
Drawings:
WRONG: [How its looks now][1]
RIGHT: [How it should be][2]
[1]: http://i.stack.imgur.com/Iwc1h.png
[2]: http://i.stack.imgur.com/f1Sbd.png
Sorry for problems with understanding me, here is code:
http://jsfiddle.net/5myw4e26/
if you're using a position fixed at your navbar you can do a top div empty with float left and a height with the size of your navbar.
I managed to accomplish what you we're trying to do. It's probably not the best solution, but it works.
Using JQuery I calculated when a paragraph (p.content) and the navigation-bar collided.
There's more than enough to finetune, so you can adjust it to your needs.
JQuery
$(document).ready(function() {
$(document).scroll(function() {
$("p").each(function() {
if ($(this).offset().top <= $(document).scrollTop() + 32) {
$(this).css("opacity", "0");
} else {
$(this).css("opacity", "1");
}
});
});
});
Note that the 32 in $(this).offset().top <= $(document).scrollTop() + 32 is the height of the navigation bar.
Example:
$(document).ready(function() {
$(document).scroll(function() {
$("p").each(function() {
if ($(this).offset().top <= $(document).scrollTop() + 32) {
$(this).css("opacity", "0");
} else {
$(this).css("opacity", "1");
}
});
});
});
body {
margin: 0px;
font-family: Arial;
font-size: 12px;
min-height: 2000px;
}
nav {
width: 100%;
height: 32px;
line-height: 32px;
text-align: center;
position: fixed;
top: 0;
border-bottom: 1px solid black;
}
p.content {
margin: 12px 0px 0px 0px;
background: yellow;
}
p:first-of-type {
margin: 44px 0px 0px 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="wrapper">
<nav>
Navigation Bar
</nav>
<p class="content">Lorem ipsum dolor sit amet, consectetur adipiscing elit. In sed dolor metus. Morbi tristique nisl vel lectus rutrum, non ultricies dolor feugiat. Fusce nec dolor in purus consectetur lacinia non sit amet turpis. Donec facilisis tortor mauris, nec vulputate
massa fermentum vel. Praesent in neque quis lacus hendrerit tincidunt sed et dolor. Nullam fermentum, orci at pulvinar imperdiet, lacus libero facilisis ante, sit amet venenatis sem tortor in nibh. Ut ullamcorper porta fermentum. Praesent faucibus,
erat eget iaculis porttitor, purus purus posuere nulla, eget lacinia odio libero in lectus. Vivamus sem ex, commodo ac tortor ut, fringilla vulputate eros. Ut iaculis augue non ipsum porttitor ornare.</p>
<p class="content">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce facilisis tellus luctus ornare hendrerit. Curabitur hendrerit justo ante. Maecenas scelerisque ligula condimentum, aliquam tortor sit amet, aliquam lacus. Interdum et malesuada fames ac
ante ipsum primis in faucibus. Ut ut augue vel massa tempus laoreet. Nulla porttitor, sem ac aliquet facilisis, purus ligula pulvinar ipsum, quis volutpat enim elit sed ante. Pellentesque quis diam vestibulum, viverra elit at, sollicitudin mi. Vivamus
vehicula ex eu justo feugiat, a ullamcorper nisi commodo. Phasellus sed tortor eget purus mollis tempor at sit amet libero. Fusce tincidunt est est, tristique pretium justo feugiat eget. Donec et lacus vehicula, aliquam sapien a, eleifend tortor.</p>
<p class="content">Vivamus vitae placerat elit. Integer eleifend nibh at purus suscipit rutrum. Aliquam et fermentum mauris. Aenean gravida velit a vehicula aliquet. Duis neque tortor, luctus eget condimentum eget, venenatis eget lorem. Maecenas sed ullamcorper tellus.
Donec euismod bibendum nunc, non ullamcorper neque cursus eget. Curabitur dapibus orci non quam vestibulum ornare. Aenean tincidunt interdum justo faucibus feugiat. Proin molestie lorem ultricies neque consequat, commodo cursus nisl molestie. Donec
gravida viverra nisl, consectetur laoreet libero interdum ac. Vivamus varius vestibulum quam eu rutrum. Pellentesque id rhoncus massa.</p>
<p class="content">Nunc finibus leo mollis efficitur tempus. Suspendisse ac elit lectus. Proin auctor ipsum faucibus arcu cursus congue. Nam rutrum odio non enim euismod auctor id in justo. Ut non sagittis orci, vel tincidunt elit. Mauris odio sem, varius eget tortor
at, commodo pretium massa. Cras sed rhoncus dolor, non dictum sem. Curabitur in imperdiet turpis, in imperdiet mi. Interdum et malesuada fames ac ante ipsum primis in faucibus. Maecenas erat nisl, sagittis id eleifend ut, consequat eget orci. Aenean
blandit arcu non varius ornare.</p>
<p class="content">Pellentesque molestie consectetur lectus in iaculis. Curabitur efficitur ac nisi vitae eleifend. Morbi semper tristique ornare. Morbi in cursus mauris. Morbi et risus velit. Etiam lobortis commodo dolor, ac pulvinar dolor gravida vel. Donec sollicitudin
metus urna, eu consequat magna vehicula a. Vivamus interdum, enim non consequat ultrices, lacus enim vehicula ante, vitae tristique tellus nibh sit amet eros. Aliquam consequat eu orci id rutrum. Donec lacus eros, eleifend et viverra vitae, congue
at turpis. Quisque rhoncus fermentum ex sed lobortis. Fusce luctus, lorem vitae condimentum gravida, nibh tortor elementum nulla, id auctor nisl ex eu lectus. Donec auctor ligula sem, et porttitor neque eleifend vitae. Aliquam felis lacus, sollicitudin
laoreet dui mollis, scelerisque auctor metus.</p>
</div>

Categories

Resources