responsive height of div: shrink to a breakpoint then start growing again - javascript

I'm using an hero section to show some content.
It's responsive using the padding-bottom percentage technique and an inner absolute positioned container to center the content.
Now the catch: reaching a breakpoint, let's say 768px, and on lower window size I would like the box to start growing again.
I found some js/jQuery code around the web and was able to get the result but it only works if I load the page when the window is <768px. In that case it works brilliantly. But if the page is loaded in a larger window the below 768px resizing get lost.
This is the html:
<div class="row row-home-hero" id="hero">
<div class="cont">
<h1>Title</h1>
<h2>Subtitle</h2>
<div class="cta-hero-home">
» CTA1
<span class="cta-hero-spacer">or</span>
» CTA2
</div>
</div>
</div>
This is the JS.
It's a mess since it's a mix from different sources.
And I'm using Wordpress so I've to replace some $ with jQuery.
Please forgive me :)
function screenClass() {
if(jQuery(window).innerWidth() < 768) {
jQuery('.row-home-hero').addClass('small-hero');
} else {
jQuery('.row-home-hero').removeClass('small-hero');
jQuery('.row-home-hero').css("height", "");
}
}
// Fire.
screenClass();
// And recheck if window gets resized.
jQuery(window).bind('resize',function(){
screenClass();
});
if (document.documentElement.clientWidth < 768) {
var $li = jQuery('.small-hero'), // Cache your element
startW = $li.width(); // Store a variable reference
function setMarginDiff() {
area = 500000;
width = jQuery('.small-hero').width();
jQuery('.small-hero').height(Math.ceil(area/width/1.7));
}
setMarginDiff(); // Do on DOM ready
jQuery(window).resize(setMarginDiff); // and on resize
}
And this is the CSS
.row-home-hero {
background-position: center;
-webkit-background-size: cover;
background-size: cover;
background-repeat: no-repeat;
position: relative;
background-color: red;
}
.row-home-hero:before {
display: block;
content: "";
width: 100%;
padding-top: 46%;
}
.row-home-hero .cont {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 40%;
text-align: center;
}
a.cta-hero-link {
display: block;
width: 100px;
max-width: 80%;
line-height: 40px;
background: white;
color: #1b9fdd;
text-transform: uppercase;
text-decoration: none;
margin: 10px auto;
text-align: center;
font-weight: 500;
box-shadow: 0px 0px 7px 1px rgba(0,0,0,.4);
}
#media screen and (max-width: 768px) {
.row-pre-footer .cont div {
width: 100%;
padding: 0 5%;
float: none;
margin: 0 auto 30px;
}
.progetto-footer, .loghi-footer {
width: 100%;
max-width: 320px;
margin: 0 auto 30px;
float: none;
}
.double-box .tib-tab {
float: none;
width: 90%;
margin: 5% auto;
padding-bottom: 90%;
}
.tib-box h2, .tab-box h2 {
font-size: calc(28px + (46 - 28) * (100vw - 320px) / (768 - 320));
margin-bottom: 18vw;
}
.double-box-inner p {
font-size: 22px;
line-height: 30px;
}
.row-home-hero.small-hero {
height: 500px;
}
.row-home-hero:before {
display: block;
content: "";
width: 100%;
padding-top: 0;
}
}
And this is a working demo
Thanks!

I moved the if (document.documentElement.clientWidth < 768) { block inside the resize event. So that it gets called whenever the window is resized.
In the original version, it would only get called when the page was loaded (and only if the screen was smaller than 768). With this adjustment, it will always be rechecked when resized.
I also merged all your code into one smaller function.
var breakpoint = 768
var area = 500000
var target = $('.row-home-hero')
$(window).bind('resize', function() {
if(window.innerWidth < breakpoint) {
var width = target.width()
target.addClass('small-hero')
target.height(Math.ceil(area / width / 1.7))
} else {
target.removeClass('small-hero')
target.css('height', '')
}
})
.trigger('resize')

Related

Can I use requestAnimationFrame to smooth out scroll behaviour?

I have a small scroll effect which simulate that a logo will disappear if a lower div will scroll over it.
Currently I'm checking if two divs are intersecting. If this is true, then the height of the div of the logo will decrease with the scroll position of the div beneath.
Unfortunately, my demo is not foolproof and some fragments of the logo are still visible.
Is there a way to do this jank-free? Maybe with requestAnimationFrame?
function elementsOverlap(el1, el2) {
const domRect1 = el1.getBoundingClientRect();
const domRect2 = el2.getBoundingClientRect();
return !(
domRect1.top > domRect2.bottom ||
domRect1.right < domRect2.left ||
domRect1.bottom < domRect2.top ||
domRect1.left > domRect2.right
);
}
const el1 = document.querySelector(".logo");
const el2 = document.querySelector(".clickblocks");
let scrollPositionEl2;
let heightDifference;
const logoHeight = el1.offsetHeight;
document.addEventListener("DOMContentLoaded", () => {
var scrollDirectionDown;
scrollDirectionDown = true;
window.addEventListener("scroll", () => {
if (this.oldScroll > this.scrollY) {
scrollDirectionDown = false;
} else {
scrollDirectionDown = true;
}
this.oldScroll = this.scrollY;
// test
if (scrollDirectionDown) {
if (elementsOverlap(el1, el2) === true) {
scrollPositionEl2 = el2.getBoundingClientRect().top;
heightDifference = logoHeight - scrollPositionEl2 + 100;
//console.log(logoHeight - heightDifference);
el1.style.height = `${logoHeight - heightDifference}px`;
}
} else {
//scrolling up
scrollPositionEl2 = el2.getBoundingClientRect().top - 100;
el1.style.height = `${scrollPositionEl2}px`;
//console.log(logoHeight);
}
});
});
#import url("https://fonts.googleapis.com/css2?family=Inter:wght#900&display=swap");
.wrapper {
max-width: 100vw;
margin: 0 auto;
background-image: url("https://picsum.photos/1920/1080");
background-size: cover;
background-attachment: fixed;
height: 1200px;
position: relative;
&::after {
content: "";
position: absolute;
background: rgba(0, 0, 0, 0.3);
width: 100%;
height: 100%;
inset: 0;
}
}
body {
margin: 0;
}
main {
width: 100%;
height: 100vh;
position: relative;
z-index: 1;
}
.clickblocks {
width: 100%;
height: 200px;
display: grid;
grid-template-columns: repeat(12, (minmax(0, 1fr)));
}
.clickblock {
transition: all ease-in-out 0.2s;
backdrop-filter: blur(0px);
border: 1px solid #fff;
height: 100%;
grid-column: span 6 / span 6;
font-size: 54px;
font-weight: 700;
padding: 24px;
font-family: "Inter", sans-serif;
color: white;
text-transform: uppercase;
&:hover {
backdrop-filter: blur(10px);
}
}
.logo {
background: url("https://svgshare.com/i/ivR.svg");
width: 100%;
background-repeat: no-repeat;
background-position: top;
position: fixed;
top: 100px;
}
.logo-wrapper {
position: relative;
}
<div class="wrapper">
<main>
<div class="logo-wrapper" style="height: 390px">
<div class="logo" style="height: 300px">
</div>
</div>
<div class="clickblocks">
<div class="clickblock">
Some Content
</div>
</div>
</main>
</div>
Few things here to optimize your performance.
getBoundingClientRect() is a rather expensive calculation. If there are NO other options it's fine.
The Intersection Observer API is a lot more performant, and you can set the root element on the API. Then observe the element that is moving. This should be able to telly you if their are colliding.
Whenever you do scroll based logic, you should really try and throttle the logic so that the scroll any fires ever 16.6ms. That will reduce the number of times the calculations are made, and speed things up on the FE.
Learn how to use Google Chrome's performance tab. It can be overwhelming at first, but it gives you the ability to drill into the exact piece of code that's slowing your site down.
Learn about JS's event loop, and what's really going on under the hood. This video by Jake Archibald really help me understand it.
Hope this helped, sorry that I didn't give you an actual solution.

position sticky using javascript makes div goes outside the parent

I have a menu on the left that I want to be always sticky, I'm using javascript for that for IE11 support.
The problem I'm having is that the right div goes to the left when it's sticky and doesn't keep it's position, the second issue is that the .content div width grows when the right div is sticky.
For the javascript part, I don't know how to make the right div to stop when it reaches the footer.
EDIT:
I managed to solve the second issue, the code is updated, I also tried to add a right value for the right div so it sticks in its initial vertical position, but that's not working because it changes when the screen gets resized.
How can I solve this?
Edit 2:
For the javascript issue I found this post which helped me resolve my issue:
Make sticky/fixed element stop at footer
var sticky = document.getElementsByClassName("sticky-element")[0];
var stickyAnchor = sticky.parentNode;
var state = false;
function getAnchorOffset() {
return stickyAnchor.getBoundingClientRect().top;
}
updateSticky = function (e) {
if (!state && (getAnchorOffset() < 0)) {
sticky.classList.add("is-sticky");
sticky.parentElement.classList.add("has-sticky");
state = true;
} else if (state && (getAnchorOffset() >=0 )) {
sticky.classList.remove("is-sticky");
sticky.parentElement.classList.remove("has-sticky");
state = false;
}
}
window.addEventListener('scroll', updateSticky);
window.addEventListener('resize', updateSticky);
updateSticky();
.main-wrapper {
margin: 48px 48px 0 48px;
max-width: 1366px;
}
.wrapper {
width: 100%;
display: flex;
justify-content: space-between;
position: relative;
}
.wrapper.has-sticky .content{
margin-right: calc(199px + 72px);
}
.content {
flex: 0 1 1040px;
width: calc(1040px - 72px);
min-width: 1%;
margin-right: 72px;
height: 1200px;
background-color: #e6e9f0;
}
.nav-menu {
position: static;
flex: 0 1 199px;
width: 199px;
min-width: 199px;
color: white;
height: 300px;
background-color: #04246a;
right: 10%;
}
footer {
background-color: yellow;
height: 300px;
margin-top: 50px;
}
.is-sticky {
top: 0;
position: fixed;
}
<div class="main-wrapper">
<div class="wrapper">
<div class="content">
Main content
</div>
<div class="nav-menu sticky-element">
<nav>
Side content
</nav>
</div>
</div>
<footer>
Footer content
</footer>
</div>
Are you looking for this?
The problem on your code is that whenever you set the position of your right div to fixed it then looks for its relative parent and jumps to the upper left position inside the parent. In your case, the parent div was the .wrapper, that's why it keeps on jumping to the left side and overlaps your main content div.
I added a parent container for the .nav-menu so it will still be in the same position when scrolling. With this, your .nav-menu element won't be using the .wrapper as its main parent. This will create a smooth scroll without noticing any change in position.
Happy coding!
var sticky = document.getElementsByClassName('sticky-element')[0];
var stickyAnchor = sticky.parentNode;
var state = false;
function getAnchorOffset() {
return stickyAnchor.getBoundingClientRect().top;
}
updateSticky = function (e) {
if (!state && getAnchorOffset() < 0) {
sticky.classList.add('is-sticky');
state = true;
} else if (state && getAnchorOffset() >= 0) {
sticky.classList.remove('is-sticky');
state = false;
}
};
window.addEventListener('scroll', updateSticky);
window.addEventListener('resize', updateSticky);
updateSticky();
.main-wrapper {
margin: 48px 48px 0 48px;
max-width: 80%;
}
.wrapper {
width: 100%;
display: flex;
justify-content: space-between;
position: relative;
}
.content {
flex: 0 1 80%;
width: calc(80% - 24px);
min-width: 1%;
margin-right: 24px;
height: 1200px;
background-color: #e6e9f0;
}
.nav-container {
flex-grow: 1;
width: 20%;
min-width: 200px;
position: relative;
display: block;
}
.nav-menu {
color: white;
width: 100%;
min-width: inherit;
height: 300px;
background-color: #04246a;
}
.is-sticky {
top: 0;
position: fixed;
width: calc(20% - 97px);
}
<div class="main-wrapper">
<div class="wrapper">
<div class="content">Main content</div>
<div class="nav-container">
<div class="nav-menu sticky-element">
<nav>Side content</nav>
</div>
</div>
</div>
</div>
var sticky = document.getElementsByClassName("sticky-element")[0];
var stickyAnchor = sticky.parentNode;
var state = false;
function getAnchorOffset() {
return stickyAnchor.getBoundingClientRect().top;
}
updateSticky = function (e) {
if (!state && (getAnchorOffset() < 0)) {
sticky.classList.add("is-sticky");
state = true;
} else if (state && (getAnchorOffset() >=0 )) {
sticky.classList.remove("is-sticky");
state = false;
}
}
window.addEventListener('scroll', updateSticky);
window.addEventListener('resize', updateSticky);
updateSticky();
.main-wrapper {
margin: 48px 48px 0 48px;
max-width: 80%;
}
.wrapper {
width: 100%;
display: flex;
justify-content: space-between;
position: relative;
}
.content {
flex: 0 1 80%;
width: calc(80% - 24px);
min-width: 1%;
margin-right: 24px;
height: 1200px;
background-color: #e6e9f0;
}
.nav-menu {
position: static;
flex: 0 1 20%;
width: 20%;
min-width: 20%;
color: white;
height: 300px;
background-color: #04246a;
}
.is-sticky {
top: 0;
right:5%;
position: fixed;
}
<div class="main-wrapper">
<div class="wrapper">
<div class="content">
Main content
</div>
<div class="nav-menu sticky-element">
<nav>
Side content
</nav>
</div>
</div>
</div>

Not able to make element stick to the bottom when offscreen in IE 11, just like in css sticky

I am trying to replicate the same behavior as in this
codepen in IE 11 (does not have css sticky)
I am able to detect when the item is offscreen at the start with:
if (
$(".main-content").height() + $(".main-content").offset().top <
$(".main-footer").offset().top
)
but then after it reaches the end of the scroll (in this case the page), I did not manage to check when it goes offscreen again. It is probably something simple as subtracting the scroll to figure out if the element is offscreen, I am just stuck...
Here is a codepen where I stuck am now.
IE doesn't support <main> so you can't use this tag in IE 11. You can monitor the scroll bar changes through JavaScript, and then change its class according to the position of the element.
Here is the code you can refer to:
$(document).scroll(function() {
var scroH = $(document).scrollTop();
var viewH = $(window).height();
var contentH = $(document).height();
$('.main-footer').addClass('main-footer1')
if (scroH > 100) {}
if (contentH - (scroH + viewH) <= 100) { // The height from the bottom is less than 100px
}
if (contentH <= (scroH + viewH + 100)) {
$('.main-footer').removeClass('main-footer1')
$('.main-footer').addClass('main-footer2')
} else {
$('.main-footer').addClass('main-footer1')
$('.main-footer').removeClass('main-footer2')
}
});
body {
color: #fff;
font-family: arial;
font-weight: bold;
font-size: 40px;
}
.main-container {
max-width: 600px;
margin: 0 auto;
border: solid 10px green;
padding: 10px;
margin-top: 40px;
}
.main-container * {
padding: 10px;
background: #aaa;
border: dashed 5px #000;
}
.main-container *+* {
margin-top: 20px;
}
.main-header {
height: 50px;
background: #aaa;
}
.main-content {
min-height: 1000px;
}
.main-footer {
border-color: red;
}
.main-footer1 {
position: fixed;
bottom: 0px;
margin: 0 auto;
width: 570px;
}
.main-footer2 {
position: relative;
margin-top: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main-container">
<header class="main-header">HEADER</header>
<div class="main-content">MAIN contentH</div>
<footer class="main-footer">footer</footer>
</div>
Result in IE 11:

Unzoomable element

I want to make div with size equal to 1 screen pixel regardless current browser zoom.
It's important for me that this element will be as small as possible, but will cause line break if the next element tries to get same size as container or larger.
I used 1px but when page zoom is less then 100% it gets unstable - sometimes it works, but sometimes Chrome shrinks element to 0 and does not wrap the next element. So I hoped to enlarge element on other zooms, but I don't know how to detect it.
Seems like on my computer next snippet works fine, but in the real code similar thing works unstable if browser zoom is less than 100%. In this example I want red div to take 1px of the screen width regardless current zoom. Is that possible?
~function () {
var s = "When silver div gets too wide it should jump down..."
var i = s.length
var div = document.querySelector(".content");
setInterval(function () {
div.textContent = s.slice(0, i = ++i % (s.length + 1))
}, 100)
}()
section {
width: 15em;
height: 2em;
line-height: 2em;
border: 1px solid;
}
div {
display: inline-block;
vertical-align: top;
height: 100%;
}
.narrow {
width: 1px;
background: red;
margin-bottom: 1px;
}
.content {
background: silver;
white-space: nowrap;
}
<section><div class=narrow></div><div class=content></div></section>
For webkit it's possible with media queries:
~function () {
var s = "When silver div gets too wide it should jump down..."
var i = s.length
var div = document.querySelector(".content");
setInterval(function () {
div.textContent = s.slice(0, i = ++i % (s.length + 1))
}, 100)
}()
section {
width: 15em;
height: 2em;
line-height: 2em;
border: 1px solid;
}
div {
display: inline-block;
vertical-align: top;
height: 100%;
}
.narrow {
width: 1px;
background: red;
margin-bottom: 1px;
}
#media (-webkit-min-device-pixel-ratio: .1 ) { .narrow { width: 10px; } }
#media (-webkit-min-device-pixel-ratio: .25) { .narrow { width: 4px; } }
#media (-webkit-min-device-pixel-ratio: .3 ) { .narrow { width: 3px; } }
#media (-webkit-min-device-pixel-ratio: .5 ) { .narrow { width: 2px; } }
#media (-webkit-min-device-pixel-ratio: 1 ) { .narrow { width: 1px; } }
.content {
background: silver;
white-space: nowrap;
}
<section><div class=narrow></div><div class=content></div></section>

Hide Sticky Div Once Scrolling Past Next Parent Div

I'm trying to hide a "sticky" div once it scrolls past the next parent div. I've currently successfully have it so it appears after scrolling "y > 100" but I'm having a lot of trouble getting the "Sticky Note" to disappear after scrolling past #break.
Example below.
http://codepen.io/anon/pen/BojKBx
$(document).scroll(function() {
var y = $(this).scrollTop();
if (y > 100) {
$('.bottomMenu').fadeIn();
} else {
$('.bottomMenu').fadeOut();
}
});
.bottomMenu {
display: none;
position: fixed;
bottom: 0;
width: 50%;
height: 60px;
border-bottom: 1px solid #000;
z-index: 1;
margin: 0 auto;
left: 50%;
margin-left: -500px;
text-align: center;
}
#header {
font-size: 50px;
text-align: center;
height: 60px;
width: 100%;
background-color: red;
}
#container {
height: 2500px;
}
#break {
text-align: center;
font-size: 30px;
margin-bottom: 300px;
width: 100%;
background-color: yellow;
}
#footer {
height: 60px;
background-color: red;
width: 100%;
bottom: 0;
}
<div id="header">Home</div>
<div class="bottomMenu">
<h2>Sticky Note</h2>
</div>
<div id="container"></div>
<div id="break">Should Not Be Seen After This Point</div>
<div id="footer"></div>
You can get Y position of a div (its vertical offset starting from the top of the page), and then add condition to show sticky note only when you're below the required "Y" coordinate, and above the required div. Example:
http://codepen.io/anon/pen/EVPKyP
Javascript code:
$(document).scroll(function () {
var bodyRect = document.body.getBoundingClientRect(),
elemRect = document.getElementById("break").getBoundingClientRect(),
offset = elemRect.top - bodyRect.top - window.innerHeight;
var y = $(this).scrollTop();
if (y > 100 && y < offset) {
$('.bottomMenu').fadeIn();
} else {
$('.bottomMenu').fadeOut();
}
});
Sources:
Retrieve the position (X,Y) of an HTML element
screen width vs visible portion

Categories

Resources