how to set a variable based on screen height - javascript

Using the code below a video plays as the user scrolls down the page. this creates an issue because i am using content blocks that are 100vh. When the window gets taller, the video is no longer playing at the speed and duration to line up with each html content block that plays over it.
How do I change the the variable playbackConst based on screen height?
enterView({
selector: '.home-slide',
enter: function(el) {
el.classList.add('entered');
},
exit: function(el) {
el.classList.remove('entered');
},
})
var frameNumber = 0, // start video at frame 0
// lower numbers = faster playback
playbackConst = 900,
// select video element
vid = document.getElementById('v0');
// var vid = $('#v0')[0]; // jquery option
// Use requestAnimationFrame for smooth playback
function scrollPlay() {
var scrollTop = document.querySelector(".home-slider-container").scrollTop;
var frameNumber = scrollTop / playbackConst;
vid.currentTime = frameNumber;
window.requestAnimationFrame(scrollPlay);
}
window.requestAnimationFrame(scrollPlay);

If you use your playbackConst as a ratio of the scrollTop / screenHeight, you can adjust it manually at a random screen size, and it should work the same at different sizes.
A ratio of 1 means that 1 second of video will play when scrolling by 100vh, a ratio of 1.5 means that 1.5 seconds will play when scrolling by 100vh, etc.
Demo:
var frameNumber = 0,
playbackConst = 1,
vid = document.getElementById('v0'),
homeSliderContainer = document.querySelector(".home-slider-container");
function scrollPlay() {
var scrollTop = homeSliderContainer.scrollTop,
screenHeight = window.innerHeight,
frameNumber = (scrollTop / screenHeight) * playbackConst;
vid.currentTime = frameNumber;
window.requestAnimationFrame(scrollPlay);
}
window.requestAnimationFrame(scrollPlay);
* { box-sizing: border-box; }
body { margin: 0; padding: 0; background: #222; }
#v0, .home-slider-container {
position: fixed;
width: 100%;
height: 100%;
}
.home-slider-container {
overflow: auto;
background: rgba(0,0,0,.4);
color: #fff;
font-family: Arial, Helvetica, sans-serif;
padding: .5em 2em;
}
<video id="v0">
<source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
<source src="https://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg">
</video>
<div class="home-slider-container">
<h1>Hello, world</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse sodales sit amet mauris nec vulputate. Aliquam erat volutpat.</p><p>Suspendisse orci sem, iaculis sed ullamcorper non, vehicula vitae nisl. Phasellus vestibulum scelerisque lacinia. Ut a nisl dictum, cursus sem eget, dignissim eros. Maecenas eget dolor eget augue luctus cursus. </p><p>Sed faucibus pulvinar tincidunt. Donec a dolor elementum, lobortis est vel, blandit velit. </p><h1>Hello world, again</h1><p>Quisque facilisis tortor iaculis arcu dignissim, quis consectetur neque blandit. Pellentesque malesuada odio imperdiet velit ullamcorper, sit amet porta justo maximus. Aenean accumsan, tortor eget.</p><p>Scelerisque varius, nunc tellus malesuada lacus, ut interdum metus ante eu orci. Nullam porttitor vel neque vitae faucibus. Integer interdum pellentesque ligula sed aliquet.</p><h1>Hello, world once more</h1><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse sodales sit amet mauris nec vulputate. Aliquam erat volutpat.</p><p>Suspendisse orci sem, iaculis sed ullamcorper non, vehicula vitae nisl. Phasellus vestibulum scelerisque lacinia. Ut a nisl dictum, cursus sem eget, dignissim eros. Maecenas eget dolor eget augue luctus cursus. </p><p>Sed faucibus pulvinar tincidunt. Donec a dolor elementum, lobortis est vel, blandit velit. </p><h1>Hello world, one last time</h1><p>Quisque facilisis tortor iaculis arcu dignissim, quis consectetur neque blandit. Pellentesque malesuada odio imperdiet velit ullamcorper, sit amet porta justo maximus. Aenean accumsan, tortor eget.</p><p>Scelerisque varius, nunc tellus malesuada lacus, ut interdum metus ante eu orci. Nullam porttitor vel neque vitae faucibus. Integer interdum pellentesque ligula sed aliquet.</p>
</div>

Related

Make mobile view stick to Portrait mode while on landscape with +90 degrees

The issue:
I want the visitors to always see my site in portrait mode
I have gone through many links and have a working solution when mobile is turned to the landscape mode with -90 degrees
The issue I am facing is when mobile is turned +90 degrees. I cannot scroll the content at all when it's rotated +90 degrees. How do I make it so that the content is still scrollable even when it's rotated +90 degrees?
To see the issue:
Run the code snippet below (in full page) on any mobile turned to landscape mode (or on Developer Tools with mobile mode on while on landscape orientation)
You will see the issue I get with rotating by +90 degrees
To see the working version (-90 degrees), change the rotator-right class to rotator in my JS code below
The code I have:
(function() {
function myFunction() {
var wSH = window.screen.height;
var wI = window.innerHeight;
var dBC = document.body.clientHeight;
var wO = window.orientation;
document.getElementById("wSH").textContent = wSH;
document.getElementById("wI").textContent = wI;
document.getElementById("wO").textContent = wO;
document.getElementById("dBC").textContent = dBC;
var bodyDocument = document.body;
var iosDevice = /iPad|iPhone|iPod/.test(navigator.userAgent) &&
!window.MSStream;
if (window.matchMedia('(orientation: landscape)').matches &&
(
(window.screen.height < 425) /* for android */ ||
(iosDevice && window.innerHeight < 425) /* for iOS */
)
) {
bodyDocument.classList.add('rotator-right');
} else {
bodyDocument.classList.remove('rotator-right');
}
document.getElementsByTagName('body')[0].style.display = 'none';
setTimeout(function() {
document.getElementsByTagName('body')[0].style.display = 'block';
}, 200);
setTimeout(function() {
//console.log('inside rotator-right, with document.body.scrollHeight :', document.body.scrollHeight);
}, 100);
}
window.addEventListener("resize", myFunction);
myFunction();
})();
#media screen and (orientation:landscape) {
.rotator {
transform: scale(0.95) rotate(270deg);
transform-origin: top right;
position: relative;
top: 0px;
left: -100vh;
height: 100vw;
width: 100vh;
overflow-y: hidden;
}
.rotator-right {
transform: scale(0.93) rotate(90deg);
transform-origin: top right;
position: relative;
width: 100vh;
top: 50vw;
left: 42vw;
overflow-y: hidden;
}
}
<body id='body'>
<div class='container'>
<p>Click the button to display this frame's height and width.</p>
<p id="demo"></p>
<p>window.scroll.height :
<span id="wSH"></span>
</p>
<p>window.innerHeight :
<span id="wI"></span>
</p>
<p>document.body.clientHeight :
<span id="dBC"></span>
</p>
<p>window.orientation :
<span id="wO"></span>
</p>
<button>Try it</button>
<br />
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla ac magna nec nisi accumsan blandit. Quisque feugiat commodo sapien quis pharetra. Sed elit justo, volutpat ac eleifend eu, aliquet in orci. Proin fermentum purus nec ante molestie sodales.
Cras malesuada nunc purus, id iaculis magna suscipit nec. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam pulvinar eu lectus eu sollicitudin. Integer mauris sem, posuere vel est a, eleifend pulvinar
lectus. Duis sapien velit, tristique imperdiet purus nec, scelerisque porta massa. Proin commodo faucibus purus, in volutpat lectus maximus sed. Suspendisse potenti.
</p>
<p>
Curabitur maximus elementum nibh, at rhoncus dolor auctor in. Donec ultrices enim ac est sollicitudin euismod. Mauris tempor eget dolor sit amet consequat. Suspendisse volutpat efficitur eros, vitae imperdiet tellus. Vestibulum aliquam nunc eget ante
porta gravida. Aliquam cursus fermentum accumsan. Interdum et malesuada fames ac ante ipsum primis in faucibus. Curabitur condimentum tempus mollis. Suspendisse luctus posuere sapien, ut pharetra lacus eleifend ut.
</p>
<p>
Morbi eu finibus quam. Morbi pharetra mollis diam id hendrerit. Etiam rhoncus, dolor quis hendrerit consectetur, est urna efficitur erat, in vestibulum nunc erat eget sapien. Curabitur ut massa semper, feugiat quam eu, rhoncus tortor. Ut quis convallis
diam, et euismod sem. Cras volutpat libero id nulla varius, at egestas elit consectetur. Nulla posuere neque risus, eu mollis dolor vehicula ut. Donec a ipsum eu justo malesuada lacinia in porta nibh. Aenean risus erat, molestie elementum eros vitae,
tempor porta lacus. Fusce et bibendum est. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Maecenas vel est ac justo vehicula commodo eget eget magna. Etiam vitae aliquet eros, rutrum porta ligula. Nulla at
fringilla lacus, sed commodo justo. Aenean imperdiet maximus tortor sed volutpat. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</p>
<p>
Curabitur finibus dictum condimentum. Nulla scelerisque dui elit, sit amet lobortis tellus mollis ut. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Pellentesque ac ex sapien. Maecenas ac pellentesque nisi, id mattis
ligula. Sed lacinia feugiat ultricies. Sed ultrices facilisis efficitur. Vestibulum quis libero nec quam convallis mattis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam lacus neque, sodales sit amet facilisis eu, viverra vel nulla.
Nullam nec dapibus metus. Aenean pulvinar molestie dolor. In hac habitasse platea dictumst.
</p>
<p>
Nunc commodo magna id nisl ultricies porta. Nulla eget purus et mi malesuada hendrerit. Aenean euismod mauris placerat est dapibus, venenatis posuere lacus fermentum. Cras purus lorem, tristique non semper sit amet, pulvinar a ligula. Vestibulum ante
ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse ultricies ultrices posuere. Nulla eu pellentesque ante. Curabitur consequat odio eget purus vestibulum, nec vestibulum lacus mollis. Etiam cursus, ipsum vehicula
auctor rhoncus, diam massa fermentum nibh, ac tincidunt neque arcu et risus.</p>
<hr />
<p>--------- This is the last line ---------</p>
</div>
</body>
What went wrong?
I figured out what was wrong. When you're rotating to the left by 90 degrees (-90 degrees) with a transform-origin: top right, the box extends the containing html to the right, thus causing it to be scrollable to the right.
However, when you're rotating to the right by 90 degrees (+90 degrees) with a transform-origin: top left, the box extends the containing html to the left and this does not cause it to be scrollable to the left. There has been a discussion about this particular scenario here at SO. Do try reading it.
Workaround
Knowing that, we can instead manipulate the transform-origin to bottom left so that the box rotates in such a way that it extends the containing html to the right and causes the scrollbar to appear. However, doing this, we need to adjust it so that the position is correct. To do that, we can use another transform function, which is translate. I changed your .rotator and .rotator-right classes to utilize translateX and translateY before rotating so that the position after rotation is correct.
(I recommend playing with transform function. Try making one item that applies rotate before translate and one item that applies translate before rotate. The results are different! You'll learn something new.)
I advise trying to adjust transform and overflow-y values to see what I mean by the box extending the containing html to the right and left on both .rotator and .rotator-right class.
Here's a working solution. I added configured your CSS part on .rotator-right and .rotator. You're not using left or top anymore to adjust the position, you're giving that control to transform function wholly. Try running it on full-screen and enable mobile mode on your browser.
function myFunction() {
var wSH = window.screen.height
var wI = window.innerHeight
var dBC = document.body.clientHeight
var wO = window.screen.orientation.type
document.getElementById("wSH").textContent = wSH
document.getElementById("wI").textContent = wI
document.getElementById("wO").textContent = wO
document.getElementById("dBC").textContent = dBC
var bodyDocument = document.body;
var iosDevice = /iPad|iPhone|iPod/.test(navigator.userAgent) &&
!window.MSStream;
if (window.matchMedia('(orientation: landscape)').matches &&
(
(window.screen.height < 425) /* for android */ ||
(iosDevice && window.innerHeight < 425) /* for iOS */
)
) {
bodyDocument.classList.add('rotator-right')
} else {
bodyDocument.classList.remove('rotator-right')
}
document.getElementsByTagName('body')[0].style.display = 'none';
setTimeout(function() {
document.getElementsByTagName('body')[0].style.display = 'block';
if (bodyDocument.classList.contains('rotator-right')) window.scrollTo(bodyDocument.getBoundingClientRect().width, 0)
}, 200);
}
window.addEventListener("resize", myFunction);
myFunction();
* {
box-sizing: border-box;
}
body,
html {
margin: 0;
}
p {
margin: 0;
padding: 16px 0;
}
#media screen and (orientation:landscape) {
.rotator {
transform-origin: top right;
width: 100vh;
/* Try playing with these properties to see the transformation */
/* Use scale at the very end of transform if needed */
transform: translateX(-100%) rotate(-90deg);
transition: all .5s ease;
overflow-y: hidden;
}
.rotator-right {
transform-origin: bottom left;
width: 100vh;
/* Try playing with these properties to see the transformation */
/* Use scale at the very end of transform if needed */
transform: translateY(-100%) rotate(90deg) scale(0.85);
transition: all .5s ease;
overflow-y: hidden;
}
}
<body id='body'>
<div class='container'>
<p>Click the button to display this frame's height and width.</p>
<p id="demo"></p>
<p>window.scroll.height :
<span id="wSH"></span>
</p>
<p>window.innerHeight :
<span id="wI"></span>
</p>
<p>document.body.clientHeight :
<span id="dBC"></span>
</p>
<p>window.orientation :
<span id="wO"></span>
</p>
<button>Try it</button>
<br />
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla ac magna nec nisi accumsan blandit. Quisque feugiat commodo sapien quis pharetra. Sed elit justo, volutpat ac eleifend eu, aliquet in orci. Proin fermentum purus nec ante molestie sodales.
Cras malesuada nunc purus, id iaculis magna suscipit nec. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam pulvinar eu lectus eu sollicitudin. Integer mauris sem, posuere vel est a, eleifend pulvinar
lectus. Duis sapien velit, tristique imperdiet purus nec, scelerisque porta massa. Proin commodo faucibus purus, in volutpat lectus maximus sed. Suspendisse potenti.
</p>
<p>
Curabitur maximus elementum nibh, at rhoncus dolor auctor in. Donec ultrices enim ac est sollicitudin euismod. Mauris tempor eget dolor sit amet consequat. Suspendisse volutpat efficitur eros, vitae imperdiet tellus. Vestibulum aliquam nunc eget ante
porta gravida. Aliquam cursus fermentum accumsan. Interdum et malesuada fames ac ante ipsum primis in faucibus. Curabitur condimentum tempus mollis. Suspendisse luctus posuere sapien, ut pharetra lacus eleifend ut.
</p>
<p>
Morbi eu finibus quam. Morbi pharetra mollis diam id hendrerit. Etiam rhoncus, dolor quis hendrerit consectetur, est urna efficitur erat, in vestibulum nunc erat eget sapien. Curabitur ut massa semper, feugiat quam eu, rhoncus tortor. Ut quis convallis
diam, et euismod sem. Cras volutpat libero id nulla varius, at egestas elit consectetur. Nulla posuere neque risus, eu mollis dolor vehicula ut. Donec a ipsum eu justo malesuada lacinia in porta nibh. Aenean risus erat, molestie elementum eros vitae,
tempor porta lacus. Fusce et bibendum est. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Maecenas vel est ac justo vehicula commodo eget eget magna. Etiam vitae aliquet eros, rutrum porta ligula. Nulla at
fringilla lacus, sed commodo justo. Aenean imperdiet maximus tortor sed volutpat. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</p>
<p>
Curabitur finibus dictum condimentum. Nulla scelerisque dui elit, sit amet lobortis tellus mollis ut. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Pellentesque ac ex sapien. Maecenas ac pellentesque nisi, id mattis
ligula. Sed lacinia feugiat ultricies. Sed ultrices facilisis efficitur. Vestibulum quis libero nec quam convallis mattis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam lacus neque, sodales sit amet facilisis eu, viverra vel nulla.
Nullam nec dapibus metus. Aenean pulvinar molestie dolor. In hac habitasse platea dictumst.
</p>
<p>
Nunc commodo magna id nisl ultricies porta. Nulla eget purus et mi malesuada hendrerit. Aenean euismod mauris placerat est dapibus, venenatis posuere lacus fermentum. Cras purus lorem, tristique non semper sit amet, pulvinar a ligula. Vestibulum ante
ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse ultricies ultrices posuere. Nulla eu pellentesque ante. Curabitur consequat odio eget purus vestibulum, nec vestibulum lacus mollis. Etiam cursus, ipsum vehicula
auctor rhoncus, diam massa fermentum nibh, ac tincidunt neque arcu et risus.</p>
<hr />
<p>--------- This is the last line ---------</p>
</div>
</body>
One unrelated concern of mine: you used this code to detect if a device is iOS: /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;. I can't seem to find a proper documentation on that so it may be inaccurate code. Furthermore, from MDN about user agent sniffing:
It's worth re-iterating: it's very rarely a good idea to use user agent sniffing. You can almost always find a better, more broadly compatible way to solve your problem!
Also, it seems like Safari (iOS) also supports window.screen.height.

Resizing div containing text on change of window size

I have implemented a function for changing the size of a div containing text, debounced for x amount of time.
And this is working when reducing the screen size, however, it does not work when expanding the screen back again.
This may be due to property scrollHeight, however I am unsure of a better way of implementing this.
I do not wish to use JQuery, please help.
https://codepen.io/physicsboy/pen/BayoLZX
const box = document.getElementById('box');
const scrl = box.scrollHeight;
box.style.height = `${scrl}px`;
console.log({box});
window.addEventListener('resize', _.debounce(() => {
console.log('debounced');
reset()
}, 500));
function reset() {
console.log('resizing');
const scrlHeight = box.scrollHeight;
console.log(`height: ${box.style.height} - scrollheight: ${scrlHeight}`);
box.style.height = `${scrlHeight}px`;
}
#box {
margin: auto auto;
padding: 20px;
max-width: 500px;
height: 200px;
background: lightgrey;
overflow: hidden;
}
<div id="box">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean non dolor nec risus cursus convallis. Sed tempor libero eu est elementum, id molestie purus cursus. Nunc pulvinar metus non ante tincidunt tempus. Proin metus mi, varius sed purus et, feugiat auctor lectus. Pellentesque elementum dui quis nunc consectetur, vitae iaculis risus laoreet. Fusce velit leo, tristique vitae faucibus eget, sagittis sed libero. Duis eleifend interdum vulputate. Vivamus vehicula commodo leo, quis rhoncus mi pharetra nec. Vivamus elementum sodales arcu nec consectetur. Nullam rhoncus risus metus, id rhoncus lacus vulputate vel. Nam sit amet egestas arcu, et ornare elit. Pellentesque fringilla volutpat urna, vel ullamcorper velit volutpat at. Pellentesque convallis tristique consequat. Etiam at diam vitae urna bibendum maximus. Nulla elementum, ex vitae tempor egestas, sem sapien pulvinar orci, et scelerisque dolor ante at nisi.
Donec in urna sed est tincidunt gravida. Proin ullamcorper sed nunc et scelerisque. Mauris sit amet arcu a odio tincidunt hendrerit. In consectetur justo ipsum, vel posuere erat tincidunt vel. Nullam dignissim ornare nunc, a porttitor felis placerat in. Etiam feugiat sem sit amet tristique congue. Donec ut arcu sit amet mauris volutpat pellentesque a a felis. Quisque purus tellus, placerat in congue nec, lacinia in lectus. Nam eget ante faucibus, facilisis odio id, dignissim lorem. Vivamus porta pharetra velit a cursus. Phasellus ac volutpat ex, nec cursus sem. Pellentesque congue sem consectetur, consectetur justo at, gravida ex. Quisque est nunc, tempus sed massa sed, consequat fringilla nulla.
Phasellus consectetur, velit id suscipit volutpat, mauris mi tempus augue, sit amet dapibus dolor ipsum eget dui. Vestibulum finibus lectus facilisis feugiat accumsan. Duis lectus felis, blandit et massa ut, eleifend sagittis lacus. Pellentesque imperdiet pharetra nisi eget venenatis. Nullam tincidunt leo nec sem lacinia auctor.
</div>
Remove jQuery and height from CSS, Use below code for CSS
#box {
margin: auto auto;
padding: 20px;
max-width: 500px;
background: lightgrey;
}
Hope it will work for you.
You might not need jQuery, just use viewport width unit "VW" .
Try this :
#box {
margin: auto auto;
padding: 20px;
max-width: 500px;
background: lightgrey;
overflow: hidden;
width: 80vw;
height:auto
}

Trigger image animation when page section visible with jQuery

I have a link button that links to a section of my page. When it's clicked or when that section of the page is scrolled to, I'd like to add a class fadeInUpAnimation to the img element below below. The image should have an opacity of 0 when it begins--I guess I can just set the opacity to 0 before the animation class is added.
<img src="img/circle-portrait-small.png" class="portrait">
This is the animation:
#keyframes fadeInUp {
from {
/* x, y axis */
transform: translate(0, 80px);
opacity: 0;
}
to {
transform: translate(0, 0);
opacity: 1
}
}
.fadeInUpAnimation {
animation-duration: 1.5s;
animation-name: fadeInUp;
}
I prefer a jQuery method since I already have a jQuery file, but it's not necessary.
Any suggestions?
This would be a good use case for the JavaScript IntersectionObserver API. Although it's a relatively new technology, it has 84% adoption and is more efficient than checking every element's position in a scroll handler.
I'd also recommend replacing your animations with transitions, since transitions are tailored specifically to this kind of one-time intro animation. By removing a class that hides the element rather than adding one that shows it, we can ensure that the animation only occurs once, i.e., when the element is first scrolled into view. This will also prevent your elements from snapping back to a -80px translate if you scroll them out, without any extra work on our part.
Long story short-- if you want performance, IntersectionObservers are the way to go. If you care about 100% browser support, this may not be an option for you. The 84% support is mainly due to people using old versions of major browsers. Once people and companies update, this will become the standard.
Note: I think the Stack Snippet is messing with this a little bit, but if you click the "Full Page" link after running it, it displays as normal. If you shrink your viewport after doing this, you can see they come in one-at-a-time exactly as intended.
const intersect_opt = {
root: null,
rootMargin: '80px',
threshold: 1.0
};
const intersect_observer = new IntersectionObserver(function(entries, observer) {
entries.forEach(entry => {
if (entry.intersectionRatio === 1) {
entry.target.classList.remove("hidden");
}
});
}, intersect_opt);
document.querySelectorAll(".box").forEach(e => {
intersect_observer.observe(e);
});
.box {
width: 100px;
height: 100px;
background: forestgreen;
transition: opacity 1.5s linear, transform 1.5s linear;
}
.hidden {
opacity: 0;
transform: translate(0, 80px);
}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut viverra nulla at libero efficitur, non tristique felis mollis. Curabitur mollis ipsum in porttitor facilisis. Mauris vulputate magna non sapien ornare pharetra. Vestibulum ac vestibulum massa, ac dignissim justo. Nulla eu purus erat. Curabitur iaculis porttitor ex. Nulla elementum elit sit amet odio faucibus lacinia. Sed a fringilla lectus. Pellentesque accumsan ipsum id lectus molestie consectetur. Sed leo orci, vehicula nec dolor vitae, malesuada hendrerit ex. Morbi elementum ante eu sapien vestibulum, ac imperdiet velit sagittis. Nulla imperdiet ultrices interdum. Nulla interdum dui eu nisl fringilla, non facilisis ipsum maximus. Mauris aliquam ullamcorper justo sit amet eleifend.</p>
<div class="box hidden"></div>
<p>Phasellus eu ipsum eget erat laoreet tincidunt ac sit amet justo. Donec malesuada consectetur porta. Maecenas pretium urna eu malesuada posuere. Duis in sem tincidunt, tempor urna nec, vulputate eros. Curabitur ex enim, bibendum sit amet sem nec, viverra semper mauris. Aenean euismod consectetur condimentum. Fusce sit amet ante nulla. Curabitur auctor libero blandit semper rhoncus.</p>
<div class="box hidden"></div>
<p>Suspendisse cursus ullamcorper magna et pellentesque. Donec nec risus vehicula ex suscipit ultrices. Mauris et tincidunt turpis, dignissim iaculis metus. Sed condimentum orci non lectus fermentum facilisis. Pellentesque vel dignissim elit. Nullam cursus lobortis ante et tristique. Integer consectetur justo ipsum, et iaculis ligula volutpat eu. In non nisi eu ex rhoncus tincidunt.</p>
<div class="box hidden"></div>
<p>Sed sagittis tincidunt tellus, ut blandit diam molestie vel. Praesent cursus dolor nisl, et laoreet nisl mattis vitae. Vivamus porta vel lorem in consectetur. Nulla rutrum, odio viverra sodales cursus, sem velit ultrices mi, a ultrices ex tellus id ligula. Aenean venenatis dui lectus, id venenatis velit malesuada ac. Nunc ultricies fringilla sem in eleifend. Praesent dapibus eu risus et consequat. Duis felis felis, iaculis nec malesuada id, sagittis id augue. Fusce a hendrerit nisl. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed varius commodo sem sit amet dignissim. Mauris venenatis sagittis quam et pellentesque. Suspendisse potenti.</p>
<div class="box hidden"></div>
<p>Donec in vehicula orci, non mollis erat. Sed luctus elementum est, sed accumsan diam porttitor vel. Nunc efficitur malesuada feugiat. Cras tempus vestibulum odio, et accumsan erat tincidunt nec. Nam vestibulum lectus suscipit diam tempor, vitae interdum elit cursus. Fusce accumsan libero vel congue efficitur. In feugiat, nibh placerat hendrerit suscipit, sapien nisi placerat augue, sed sodales nulla lacus iaculis velit. Nunc quis eros sit amet justo interdum iaculis. Proin auctor, eros ut aliquam rhoncus, dolor risus egestas sapien, eu facilisis est purus nec neque. Sed luctus tellus et mattis elementum. Etiam tempor justo ut viverra fermentum. Quisque pretium quam nibh, ut dictum est aliquam vitae. In hac habitasse platea dictumst. Quisque sit amet massa accumsan, ultricies libero quis, laoreet lectus. Donec gravida interdum mi in euismod. Duis aliquam lorem velit, sed maximus purus mattis eu.</p>
You can bind a function to the document's scroll event, so that it will check if your element is visible every time the user scrolls:
$(document).on('scroll', function(){
...
});
Then, since we'll have to run some calculations, assign the window height value to a variable:
var wHeight = window.innerHeight;
var yScroll = window.scrollY || window.pageYOffset;
And take your element's Y position:
var elementPosition = $('.portrait').offset().top;
Now, put it all together:
$(document).on('scroll', function(){
var wHeight = window.innerHeight;
var yScroll = window.scrollY || window.pageYOffset;
var elementPosition = $('.portrait').offset().top;
if(wHeight + yScroll > elementPosition + $('.portrait').height()) {
$('.portrait').addClass('fadeInUpAnimation ');
}
});
.blank {
display: block;
height: 1600px;
}
.portrait {
display: block;
width: 200px;
height: 200px;
background-color: rgba(150,0,0,1);
opacity: 0;
transform: translate(120px, 0);
transition: all 0.5s cubic-bezier(.2,.7,.2,1.1);
}
.fadeInUpAnimation {
opacity: 1;
transform: translate(0, 0);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="blank">
Scroll down!
</div>
<div class="portrait">
</div>
<div class="blank">
</div>

why does this not work if the page is already slightly scrolled?

I have this effect that makes the header change from fixed to absolute and scroll with the rest of the page when a target div hits it.
The problem is that if the page is slightly scrolled on load then it breaks the calculations that tell the header where to sit on the page is wrong and it ruins the effect. I cant work out the issue.
Here is the code:
window.onresize = function(event) {
targetTopPos = targetEl.offsetTop + 100;
console.log(targetTopPos);
};
const headerEl = document.querySelector('header')
const targetEl = document.querySelector('#target')
let targetTopPos = targetEl.getBoundingClientRect().top
let isHeaderFixed = true
document.onscroll = () => {
let targetTopOffset = targetEl.getBoundingClientRect().top
console.log(targetTopOffset);
if (isHeaderFixed && targetTopOffset < 100) {
headerEl.style.position = 'absolute'
headerEl.style.top = `${targetTopPos - 100}px`
isHeaderFixed = !isHeaderFixed
}
if (!isHeaderFixed && targetTopOffset >= 100) {
headerEl.style.position = 'fixed'
headerEl.style.top = '0px'
isHeaderFixed = !isHeaderFixed
}
}
body {
padding: 0;
margin: 0;
position: relative;
}
header {
position: fixed;
height: 100px;
width: 100%;
background: lightblue;
}
.content {
line-height: 100px;
}
.target {
width: 100%;
background: red;
}
<header>
Custom header
</header>
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam suscipit tellus urna, ut tristique felis lobortis sed. Phasellus maximus at magna mattis vulputate. Pellentesque tempor, urna vitae congue pellentesque, est mauris faucibus nulla, vitae molestie leo purus a leo. Curabitur ut mi ac sem finibus consectetur a blandit massa. Morbi ornare tincidunt ipsum, et accumsan erat fringilla a. Cras egestas, nibh vel condimentum ultrices, nunc ipsum tempus magna, eu ullamcorper tortor magna id lacus. Morbi euismod lacus a ligula rutrum, in aliquet lectus blandit. Nam placerat sollicitudin lectus eu ornare. Etiam placerat diam eget magna blandit rutrum. Nulla et luctus massa. Sed sit amet mauris in magna tincidunt consequat. Proin mattis sit amet arcu a gravida. Nullam tempor urna nec dolor convallis consectetur sit amet a elit. Cras ut odio nec lacus efficitur porta nec sit amet justo.
</div>
<div id="target" class="target">target</div>
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam suscipit tellus urna, ut tristique felis lobortis sed. Phasellus maximus at magna mattis vulputate. Pellentesque tempor, urna vitae congue pellentesque, est mauris faucibus nulla, vitae molestie leo purus a leo. Curabitur ut mi ac sem finibus consectetur a blandit massa. Morbi ornare tincidunt ipsum, et accumsan erat fringilla a. Cras egestas, nibh vel condimentum ultrices, nunc ipsum tempus magna, eu ullamcorper tortor magna id lacus. Morbi euismod lacus a ligula rutrum, in aliquet lectus blandit. Nam placerat sollicitudin lectus eu ornare. Etiam placerat diam eget magna blandit rutrum. Nulla et luctus massa. Sed sit amet mauris in magna tincidunt consequat. Proin mattis sit amet arcu a gravida. Nullam tempor urna nec dolor convallis consectetur sit amet a elit. Cras ut odio nec lacus efficitur porta nec sit amet justo.
</div>
For some reason that code doesn't work exactly as it does on my real site, on the real site you can resize, if you are scrolled to the top, and the effect still works.
You can try this js if you want with the styles. This js adds a class to your header when it reaches a specific height of scroll.
<!--JS-->
<script language="javascript" type="text/javascript">
window.onscroll = function() {myFunction()};
function myFunction() {
if (document.body.scrollTop > 300 || document.documentElement.scrollTop > 300) {
document.getElementById("myheader").className = "sticky";
} else {
document.getElementById("myheader").className = "";
}
}
</script>
<!--HTML-->
<div id="myheader">
//logo and nav
</div>
<!--CSS-->
#myheader{
position: relative;
}
#myheader.sticky {
position: fixed;
top: 0;
left: 0;
width: 100%;
z-index: 99999;
}

What's the easiest method to keep div scrollbar at the bottom when the content in div is updated?

The code can already scroll to the bottom after a submission, but the scroll bar does not update when there is a page update.
Here is how I want the scrollbar to behave:
1) The scroll bar starts at the bottom of the div.
2) The scroll bar scrolls to the bottom of the div only if you are at the bottom of the div before the content in the php file is updated.
3) The scroll bar does not scroll to the bottom of the div if you are not at the bottom of the div before an update was made to the content in the php file.
I searched Google and here for a method to get this to work, but what I have found does not work for me in my case.
Here's the code for the div:
<div id="div1" style="position: absolute; width: 70%; height: 80%; overflow-y: auto; right: 0px; top: 0px;" >
<?php include ('content.php'); ?>
</div>
And here's the code for the javascript:
$(document).ready(function() {
$('#msg').ajaxForm({
target: '#message',
success: function() {
$("#msg")[0].reset();
$("#div1").animate({ scrollTop: $("#div1")[0].scrollHeight}, 1000);
$('#message').fadeIn('slow');
}
});
});
To detect that the scroll bar is at the bottom you can use the following
function isScrolledToBottom(el) {
return el.scrollTop == el.scrollHeight - el.clientHeight;
}
Here's an example where
Div starts scrolled down
When content is added, it checks if the div was scrolled all the way down before updating content
If it was scrolled to the bottom, it scrolls it again after updating
var div = document.getElementById('content');
// Set it to go the bottom initially
scrollToBottom(div);
document.querySelector('button').addEventListener('click', function() {
var wasAtBottom = isScrolledToBottom(div);
var scrambledText = div.innerHTML.split('').sort(function() {
return Math.random() - .5
}).join('');
div.appendChild(document.createTextNode(scrambledText));
if (wasAtBottom) {
scrollToBottom(div);
}
});
function isScrolledToBottom(el) {
return el.scrollTop == el.scrollHeight - el.clientHeight;
}
function scrollToBottom(el) {
el.scrollTop = el.scrollHeight - el.clientHeight;
}
#content {
height: 150px;
overflow: scroll;
}
<div id="content"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin luctus imperdiet venenatis. Etiam lorem nisi, ullamcorper nec neque non, ultrices elementum lectus. Ut dapibus venenatis quam sit amet imperdiet. Proin scelerisque, nunc vitae ultricies aliquam, diam ligula venenatis purus, id egestas elit turpis sit amet velit. Suspendisse facilisis vel arcu eget hendrerit. Donec non nunc aliquam, finibus ante vitae, venenatis dolor. Suspendisse pulvinar fermentum rhoncus. Proin pulvinar lectus et purus consectetur rutrum. Phasellus rutrum dolor risus, non consectetur erat posuere eget. Etiam viverra congue laoreet. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec aliquet ullamcorper finibus. Nulla ac vehicula risus. Phasellus nec fermentum quam. Donec blandit ornare ipsum ut dignissim. Etiam nec velit maximus, mollis nibh id, elementum nisi. Donec arcu nisi, sollicitudin sit amet metus sed, aliquet convallis eros. Sed lacus metus, aliquet sed sodales vitae, rutrum sollicitudin dolor. Nunc dictum, mi id egestas luctus, mi erat finibus enim, a imperdiet orci est ac elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Suspendisse potenti. Sed dignissim viverra finibus. Ut quis nulla a sapien bibendum sodales at ut nunc. Etiam volutpat ante varius tellus vulputate blandit. Aliquam turpis purus, efficitur vel lacus imperdiet, viverra auctor nisl. Aenean nunc est, tempus nec tincidunt in, malesuada in mauris. Nam dui risus, maximus et placerat in, elementum tristique leo. Fusce quis viverra enim. Curabitur congue fringilla accumsan. Curabitur vehicula aliquet malesuada. Aliquam pharetra ante vel nulla elementum, sit amet auctor mi porttitor. Mauris id varius leo. Vestibulum ac dolor id ligula iaculis aliquam. Donec porta euismod quam, eu sollicitudin nisi interdum egestas. Vestibulum et ligula velit. Nulla vel iaculis purus. Integer et est ut ipsum fringilla rhoncus. Aliquam auctor eu arcu rhoncus maximus. Sed vulputate, ipsum nec tempus sodales, neque leo hendrerit elit, a faucibus nisl ex nec lorem. Praesent varius dictum felis, sed sollicitudin diam tempor vitae. Mauris tempus justo non egestas mollis. Etiam congue odio eget velit vulputate, sit amet pharetra nulla faucibus. Cras a lorem sed ante imperdiet dapibus id blandit risus. Pellentesque nec tincidunt lacus.</div>
<button>Add content</button>

Categories