Incremental Shrink on Animated Nav Bar - javascript

I have created a fixed, animated nav bar that shrinks on scroll. Currently, it shrinks from 150 to 100 if the ypos > 10.
However, I would like to add a second stage to the shrink. So if ypos > 10 but < 40, it executes state 1 and, if it is greater than 40 it executes state 2 which will be a shrink from 100 to 50.
Problem: I can get the first stage working, but I am not sure how to watch for the second state of the shrink or how to add the second class that changes the first.
function shrink()
{
ypos = window.pageYOffset;
var topBar = document.getElementById("Top-Bar");
if(ypos > 10 && ypos < 39)
{
topBar.classList.add("shrink");
}
else if(ypos > 40)
{
topBar.classList.add("secondShrink");
}
else
{
topBar.classList.remove("shrink");
topBar.classList.add("secondShrink");
}
};
window.addEventListener("scroll", shrink)
#Top-Bar
{
height: 150px;
width: 100%;
background-color: #ccc;
display: flex;
justify-content: center;
align-items: center;
transition: all .2s ease;
position: fixed;
z-index: 2;
}
#Top-Bar.shrink
{
height: 100px;
transition: all .2s ease;
}
#Top-Bar.shrink.secondShrink
{
height: 50px;
}
.content
{
content: "";
height: 1200px;
position: relative;
z-index: 1;
}
<div id="Top-Bar">
<h1>Site Title</h1>
</div>
<div class="content"></div>
I am attempting to recreate the effect from the following page: http://www.newmediacampaigns.com/blog/responsive-site-header

As I mentioned in the comments:
On the very first scroll of the page at yPos 0, you add secondShrink to the top bar. At no point do you ever remove it, so from here on out, the top bar will always have .secondShrink. Because of this, normal .shrink will never get hit.
I've modified your code below so that only one shrink at a time is attached to the top bar. Additionally, your if and if else don't account for anything from 1-10, or 39-40. Conveniently enough, one mouse wheel click, or one down-arrow click is exactly 40 pixels.
Check out this cleaned up version:
function shrink()
{
ypos = window.pageYOffset;
var topBar = document.getElementById("Top-Bar");
if(ypos > 0 && ypos <= 40)
{
topBar.classList.remove("secondShrink");
topBar.classList.add("shrink");
}
else if(ypos > 40)
{
topBar.classList.add("secondShrink");
}
else //ypos is 0
{
topBar.classList.remove("shrink");
topBar.classList.remove("secondShrink");
}
};
window.addEventListener("scroll", shrink)
#Top-Bar
{
height: 150px;
width: 100%;
background-color: #ccc;
display: flex;
justify-content: center;
align-items: center;
transition: all .2s ease;
position: fixed;
z-index: 2;
}
#Top-Bar.shrink
{
height: 100px;
transition: all .2s ease;
}
#Top-Bar.secondShrink
{
height: 50px;
}
.content
{
content: "";
height: 1200px;
position: relative;
z-index: 1;
}
<div id="Top-Bar">
<h1>Site Title</h1>
</div>
<div class="content"></div>

Related

Line across any device and in the centre, using canvas or html,css

I'm making an app using JavaScript and JQuery, which will tell the user if there device is straight or not, basically like a spirit level. I want to draw a line a straight line across the middle of the screen and i want this to be responsive no matter the size of the device. This will be used on mobiles and tablets. I used a canvas to the draw a line and so far i'm not sure if this is the right way to approach this?
if anyone could give me any advice i would really appreciate it. Below is my canvas line so far. And I've included some rough drawing of what i mean.
const c = document.getElementById("LineCanvas");
const drw = c.getContext("2d");
drw.beginPath();
drw.moveTo(10,45);
drw.lineTo(180,47);
drw.lineWidth = 5;
drw.strokeStyle = '#006400';
drw.stroke();
If the phone is aligned straight the line will be green else red
to draw the line you can use a pseudo element from HTML or body or any specific tag that you want to use in a specific page or click , then update rotation via transform:rotate() ; or rotate3D()
example ( without javascript, rotate values will have to be taken from your device via your app ):
let level = document.querySelector("#level");
document.querySelector("#spirit").onclick = function() {
level.classList.toggle('show');
}
#level {
width: 100vw;
height: 100vh;
position: fixed;
top: 0;
left: 0;
display: none;
pointer-events: none;
}
#level.show {
display: block;
}
#level::before {
content: '';
position: absolute;
width: 200vmax;
margin: 0 -50vmax;
border-top: 1px solid;
box-shadow: 0 0 1px 5px #bee;
top: 50%;
transform: rotate(0deg);
}
#level.show~#spirit::before {
content: 'Hide';
}
#level:not(.show)~#spirit::before {
content: 'Show';
}
/* animation to fake phone device moving */
#level::before {
animation: rt 10s infinite;
}
#keyframes rt {
20% {
transform: rotate3d(1, -1, 1, -0.25turn);
}
40% {
transform: rotate3d(1, 1, 1, 0.5turn);
}
60% {
transform: rotate3d(1, -1, 1, -0.75turn);
}
80% {
transform: rotate3d(1, 1, -1, -0.5turn);
}
}
<div id="level">
<!-- to show on a single page or via js on user request -->
</div>
<button id="spirit" type=button> that spirit level</button>
While drawing a line with canvas can work you might find it more straightforward to draw it with a simple div element. When you sense a slope you can change its color to red and back to green if it's level.
Of course you will have to do some calculations to decide what angle you want the line to be - but I guess that is the whole point of your webapp to show people how far off they are.
When you know the angle you want the line to be call slope(n) where n is the number of degrees. I've also put in a simple button so the user can choose whether to show the line or not but I expect you'll have your own code for that.
On any page where you want the user to be able to show the line put this in the head:
<style>
* {
margin: 0;
padding: 0;
}
.linecontainer {
position: absolute;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
overflow: hidden;
z-index: 99999;
}
#line {
width: 200vmax;
height: 5px;
position: relative;
top: 50%;
left: calc(50vw - 100vmax);
transform: rotate(45deg);
background-color:red;
}
.hideline {
display: none;
}
#showbtn {
font-size: 20px;
background-color: blue;
color: white;
height: 2em;
width: auto;
padding: 2px;
}
</style>
and put this in the main body of the page:
<div class="linecontainer">
<div id="showbtn" onclick="document.getElementById('line').classList.toggle('hideline');">
Click me to show/hide the line
</div>
<div id="line"></div>
</div>
<script>
function slope(deg) {
let line = document.getElementById('line');
line.style.backgroundColor = ( deg%180 == 0 ) ? 'green' : 'red';
line.style.transform = 'rotate(' + deg + 'deg)';
}
</script>
Here's a snippet where you can show the line at different angles.
function slope(deg) {
let line = document.getElementById('line');
line.style.backgroundColor = ( deg%180 == 0 ) ? 'green' : 'red';
line.style.transform = 'rotate(' + deg + 'deg)';
}
* {
margin: 0;
padding: 0;
}
.linecontainer {
position: absolute;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
overflow: hidden;
z-index: 99999;
}
#line {
width: 200vmax;
height: 5px;
position: relative;
top: 50%;
left: calc(50vw - 100vmax);
transform: rotate(45deg);
background-color:red;
}
.hideline {
display: none;
}
#showbtn {
font-size: 20px;
background-color: blue;
color: white;
height: 2em;
width: auto;
padding: 2px;
}
<div class="linecontainer">
<div id="showbtn" onclick="document.getElementById('line').classList.toggle('hideline');">
Click me to show/hide the line
</div>
<div id="line"></div>
</div>
<!-- this is just for the demo -->
<div style="background-#eeeeee;font-size: 20px;position:fixed;z-index:100000;bottom:0;left:0;">How many degrees do you want me to rotate? <input style="font-size:20px;"value="45" onchange="slope(this.value);"/></div>

How to make info text appear and follow the cursor when hovering over image?

For my portfolio website, I want to include info text that becomes visible when hovering over the according image and I want the text to follow along the cursor.
I'm by no means a coding expert, so I tried to achieve the effect by replacing the default cursor with an image of the text on white background via css and the cursor-property.
However, this left me with weird gray edged around the image that the image originally doesn't have.
So I figured that this was a sloppy approach anyway and that I should rather try solving it via javascript... which left me with the following code:
$(document).bind('mousemove', function(e){
$('#tail').css({
left: e.clientX + 20,
top: e.clientY + document.body.scrollTop
});
});
#tail {
position: absolute;
background-color: #ffffff;
padding: 5px;
opacity: 0;
}
#tail p {
margin: 0px;
}
.project-01:hover > #tail {
opacity: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="project-01">
<a href="project-site-01.html">
<img src="images/project-cover-01.png" alt="Project description">
</a>
<div id="tail">
<p>Project description</p>
</div>
</div>
I am now left with text that appears when hovering over the image and it follows the cursor properly, even if the cursor position changes due to scrolling (which it didn't do properly at first, which is why I added the 'document.body.scrollTop').
The only problem: The info text is way to far away from the cursor. I tried adjusting the offset, adding '- 900' after 'document.body.scrollTop' but that only makes it look right with my specific browser height – if I switch to a smaller or bigger screen, the '- 900' of course doesn't fit anymore.
Is there anyone who can explain what I'm doing wrong on a dummy level or even better – tell me how to fix the problem? I've been trying to get that hover text effect working for literally the past two days. HELP!
PS: You can see the effect I want to create on https://playgroundparis.com
I hope this can help you!
Edit: Technically this is a duplicated. I realized the problem with scrolling that you talking about. I've found a solution in this post and I readaptated it for
your specific case.
var mouseX = 0, mouseY = 0, limitX, limitY, containerWidth;
window.onload = function(e) {
var containerObjStyle = window.getComputedStyle(document.querySelectorAll(".project-01")[0]);
containerWidth = parseFloat(containerObjStyle.width).toFixed(0);
containerHeight = parseFloat(containerObjStyle.height).toFixed(0);
var follower = document.querySelector('#tail');
var xp = 0, yp = 0;
limitX = containerWidth;
limitY = containerHeight;
var loop = setInterval(function(){
//Change the value 5 in both axis to set the distance between cursor and text.
xp = (mouseX == limitX) ? limitX : mouseX + 5;
xp = (xp < 0) ? 0 : xp;
yp = (mouseY == limitY) ? limitY : mouseY + 5;
yp = (yp < 0) ? 0 : yp;
follower.style.left = xp + 'px';
follower.style.top = yp + 'px';
}, 15);
window.onresize = function(e) {
limitX = parseFloat(window.getComputedStyle(document.querySelectorAll(".project-01")[0]).width).toFixed(0);
}
document.onmousemove = function(e) {
mouseX = Math.min(e.pageX, limitX);
mouseY = Math.min(e.pageY, limitY);
}
};
//Change the 100 value to set the fade time (ms).
$(".project-01").hover(function () {
$(this).find('#tail').fadeIn(100);
},
function () {
$(this).find('#tail').fadeOut(100);
});
#tail {
position: absolute;
background-color: #ffffff;
padding: 5px;
overflow: hidden;
}
#debug {
position: absolute;
right: 0;
top: 100px;
width: 100px;
height:100px;
background-color: red;
color: black;
}
#tail p {
margin: 0px;
}
.project-01 {
width: 300px;
overflow: hidden;
}
.project-01 img {
height: 100%;
width: 100%;
}
.project-01 a {
height: 100%;
width: 100%;
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="project-01">
<a href="project-site-01.html">
<img src="https://picsum.photos/200/300" alt="Project description">
</a>
<div id="tail">
<p>Project descriptions</p>
</div>
</div>
You can use the below code's
.description {
display: none;
position: absolute;
z-index: 2000 !important;
color: black;
padding: 15px;
margin-left: 32px;
margin-top: -200px;
top: auto;
height: auto;
width: 500px;
}
.image {
height: 200px;
width: 200px;
}
.my-image:hover + .description {
display: block;
position: absolute;
background-color: black;
color: white;
}
.description:hover {
display: block;
background-color: black;
color: white;
}
<div class="project-01">
<a href="project-site-01.html" class="my-image">
<img src="https://homepages.cae.wisc.edu/~ece533/images/monarch.png" alt="Project description" class="image">
</a>
<div id="tail" class="description">
Butterflies are insects in the macrolepidopteran clade Rhopalocera from the order Lepidoptera, which also includes moths. Adult butterflies have large, often brightly coloured wings, and conspicuous, fluttering flight.
</div>
</div>
I hope this helps i recenty made one myselff for my website a few days ago
No info cursor:
.info:hover .tooltip {
color: red;
visibility: visible;
opacity: 1;
transition: opacity 1s
}
.tooltip {
visibility: hidden;
opacity: 0;
transition: opacity 1s
}
}
.tootip:hover {
visibility: visible
}
<span class="info"><img src="https://google.com/favicon.ico">Hover Me</img> <span class="tooltip">Welcome</span></a></span>
With info cursor:
.info:hover .tooltip {
color: red;
visibility: visible;
opacity: 1;
transition: opacity 1s
}
.tooltip {
visibility: hidden;
opacity: 0;
transition: opacity 1s
}
}
.tootip:hover {
visibility: visible
}
.info {
cursor: help
}
<span class="info"><img src="https://google.com/favicon.ico">Hover Me</img> <span class="tooltip">Welcome</span></a></span>

Change transition duration during loop with requestAnimationFrame

I'm trying to change the transition duration in-between the steps of a setTimeout loop.
When the button centre is clicked, setView changes the position of content so that the inner div remains in the centre of the screen. It uses a forEach loop to change the centring using an array of inner divs.
I'd like the transition between the change from alpha inner to bravo inner to take 1s, but once it gets there the transition should be 0s so that is no lag with the centring.
Here's a codepen, then built in is getting an error.
I'm using vanilla ES6.
const content = document.querySelector('.content');
let frame;
function getBounds(div) {
const element = document.getElementById(div);
const body = element.children[0];
const {
x, y, width, height,
} = body.getBoundingClientRect();
return box = {
element, body, x: Math.round(x), y: Math.round(y), width, height,
};
}
function setView(div) {
const centerW = window.innerWidth / 2;
const centerH = window.innerHeight / 2;
const { left, top } = content.getBoundingClientRect();
content.style.left = `${(centerW + left) - (div.x + div.width / 2)}px`;
content.style.top = `${(centerH + top) - (div.y + div.height / 2)}px`;
}
function centreDiv(string) {
const outers = string.split(' ');
outers.forEach(function(outer, index) {
setTimeout(function() {
content.style.transition = 'all 0s linear'; // this works
if (frame) {
cancelAnimationFrame(frame);
}
function tick(now) {
setView(getBounds(outer));
frame = requestAnimationFrame((timestamp) => tick(timestamp, outer));
}
frame = requestAnimationFrame((timestamp) => tick(timestamp, outer));
},
5000 * index);
content.style.transition = 'all 1s linear'; // this isn't working
});
}
document.getElementById('centre').onclick = () => centreDiv(centreText.value.toLowerCase());
* {box-sizing: border-box;}
html,body,div,span {padding: 0; margin: 0; border: 0;}
.controls {
position: absolute;
z-index: 1000;
padding-top: 10px;
padding-left: 20px;
font-family: sans-serif;
color: white;
}
.content {
position: relative;
display: flex;
align-items: center;
justify-content: center;
width: 100vw;
height:100vh;
background-color: rgb(138,141,143);
transition: all 0s linear;
}
.centre {
position: absolute;
display: block;
width: 5px;
height: 5px;
background-color: white;
}
.outer {
position: absolute;
display: flex;
align-items: center;
justify-content: flex-end;
}
.inner {
display: block;
width: 30px;
height: 30px;
background-color: rgb(37,40,42);
}
.animate {
animation: spin infinite linear;
}
#alpha {
width: 80%;
height: 80%;
background-color: rgb(255,205,0);
animation-duration: 10s;
}
#bravo {
width: 30%;
height: 30%;
background-color: rgb(242,169,0);
animation-duration: 5s;
}
#keyframes spin {
100% {
transform: rotateZ(360deg);
}
}
<div class="controls">
centre: <input id="centreText" type="text" value="alpha bravo"/><button type="button" id="centre">centre</button>
</div>
<div class="content">
<div id="alpha" class="animate outer">
<div class="inner"></div>
</div>
<div id="bravo" class="animate outer">
<div class="inner"></div>
</div>
<div class="centre"></div>
</div>

How to add class on specific div when scroll?

I am playing around and practice my JS (beginner). I have created stacking panels and i hit a wall. I just can not target and add class of shadow to the moving element (only when one panel is above other, class should add).
For now i have this:
const boxes = Array.from(document.querySelectorAll(".box"));
const wrapper = document.querySelector(".wrapper");
const leftMargin = 60; //px
function scrollWrap(e) {
let scrollCoord = wrapper.scrollLeft; // horizontal scroll value
boxes.forEach((box, index) => {
let leftMarginStop = index * leftMargin;
const boxCoord = box.getBoundingClientRect();
let leftCoordPanel = boxCoord.left;
let flag = false;
//console.log({scrollCoord, leftMarginStop, leftCoordPanel, box});
if (boxCoord.left <= leftMarginStop) { // if left side of pannel is less than margin 60, 120, 180,...
//console.log("STAHP!!");
box.style.position = "sticky";
box.style.left = `${leftMarginStop}px`; // sets the left to 60, 120, 180,...
flag = true;
if (flag) {
box.classList.add("shadow");
console.log(this) //how to target each panel rather than wrapper?
} else {
box.classList.remove("shadow");
}
} else {
box.style.position = "static";
box.style.left = 0;
flag = false;
}
});
}
wrapper.addEventListener("scroll", scrollWrap);
body {
margin: 0;
padding: 0;
}
.wrapper, .box1, .box2, .box3, .box4, .box5, .box6, .box7, .box8 {
position: sticky;
height: 750px;
z-index: 1;
}
.wrapper {
width: 1442px;
border-right: 1px solid #f2f2f2;
border-bottom: 1px solid #f2f2f2;
display: flex;
overflow: scroll;
}
.wrapper .box1 {
min-width: 357px;
height: 750px;
background-color: #1a1a1a;
}
.wrapper .box2 {
min-width: 357px;
height: 750px;
background-color: #333;
}
.wrapper .box3 {
min-width: 702px;
height: 750px;
background-color: #4d4d4d;
}
.wrapper .box4 {
min-width: 630px;
height: 750px;
background-color: #666;
}
.wrapper .box5 {
min-width: 630px;
height: 750px;
background-color: #808080;
}
.wrapper .box6 {
min-width: 357px;
height: 750px;
background-color: #999;
}
.wrapper .box7 {
min-width: 630px;
height: 750px;
background-color: #b3b3b3;
}
.wrapper .box8 {
min-width: 630px;
height: 750px;
background-color: #ccc;
}
.shadow {
box-shadow: -4px 0px 40px rgba(0, 0, 0, 0.2);
}
<div class="wrapper">
<div class="box box1"></div>
<div class="box box2"></div>
<div class="box box3"></div>
<div class="box box4"></div>
<div class="box box5"></div>
<div class="box box6"></div>
<div class="box box7"></div>
<div class="box box8"></div>
</div>
If anyone can help me out, please show me code with explanation, so i can see and know what and how.
I try to do it with some flag or without, but every time the class is added when element reaches the end (left padding). I want to add class when element is on top of other element. If it is not, remove class. Also, how to make this so it works on mouse scroll wheel? I was testing this with apple magic mouse, but on scroll wheel it does not work.
Oh and please, if you see something very wrong please let me know, i am beginner and would like to learn something from this post.
For now i have managed to update my code. It works when i scroll and shadow is also applying to the panel. There is still something i wonder.
When i add shadow class i created transition. It works perfect, but when i remove shadow class it just disappears, no transition back. Why is that? I want shadow to appear and disappear in same way
How to track every single panel if it has reached the left margin, and than apply eventListener with mouse enter and mouse leave on it? So when i hover to "closed" panel, i get that item and if i hover on NOT "closed" panel i will not get item. I was trying with console.log "this" but it returned every panel i mouse entered it
How to target every panel, so i can later say, when 4th panel reaches left margin, the margin of stacked elements change?
My updated code:
const boxes = Array.from(document.querySelectorAll(".box"));
const wrapper = document.querySelector(".wrapper");
const leftMargin = 60; //px
function scrollWrap(e) {
let scrollCoord = wrapper.scrollLeft; // horizontal scroll value
boxes.forEach((box, index) => {
let leftMarginStop = (index) * leftMargin; // calculation for left margin stop (60, 120, 180,...)
const boxCoord = box.getBoundingClientRect();
const leftSideOfCurrent = boxCoord.left; // coordinarion of left side of panel
const rightSideOfCurrent = boxCoord.right; // coordinarion of right side of panel
const leftSideOfNextItem = box.nextElementSibling.getBoundingClientRect().left; // coordinarion of left side of NEXT panel
box.style.position = "sticky";
box.style.left = `${leftMarginStop}px`;
// controll shadow of first element
scrollCoord > 0 ? boxes[1].classList.add("shadow") : boxes[1].classList.remove("shadow");
// controll shadow of all 0+ elements
if (leftSideOfCurrent <= leftMarginStop) { // if left side of pannel is less than margin 60, 120, 180,...
box.nextElementSibling.classList.add("shadow");
}
// controll removal of shadow of all 0+ elements
if (leftSideOfNextItem === rightSideOfCurrent) {
box.nextElementSibling.classList.remove("shadow");
}
// when panel 5 reach left margin, left margin change from 60 to 30 to all panels
if (boxes[4] && leftSideOfCurrent < leftMarginStop) {
console.log("helo");
}
});
}
wrapper.addEventListener("scroll", scrollWrap);
body {
margin: 0;
padding: 0;
}
.wrapper, .box1, .box2, .box3, .box4, .box5, .box6, .box7, .box8 {
position: sticky;
height: 750px;
z-index: 1;
}
.wrapper {
width: 1442px;
border-right: 1px solid #f2f2f2;
border-bottom: 1px solid #f2f2f2;
display: flex;
overflow: scroll;
}
.wrapper .box0 {
min-width: 357px;
background-color: #1a1a1a;
}
.wrapper .box1 {
min-width: 357px;
background-color: #333;
}
.wrapper .box2 {
min-width: 702px;
background-color: #4d4d4d;
}
.wrapper .box3 {
min-width: 630px;
background-color: #666;
}
.wrapper .box4 {
min-width: 630px;
background-color: #808080;
}
.wrapper .box5 {
min-width: 357px;
background-color: #999;
}
.wrapper .box6 {
min-width: 630px;
background-color: #b3b3b3;
}
.wrapper .box7 {
min-width: 630px;
background-color: #ccc;
}
.shadow {
box-shadow: -4px 0px 40px rgba(0, 0, 0, 1.2);
-webkit-transition: box-shadow 0.2s cubic-bezier(0.4,-0.01, 0, 0.98);
-moz-transition: box-shadow 0.2s cubic-bezier(0.4,-0.01, 0, 0.98);
-o-transition: box-shadow 0.2s cubic-bezier(0.4,-0.01, 0, 0.98);
transition: box-shadow 0.2s cubic-bezier(0.4,-0.01, 0, 0.98);
}
<div class="wrapper">
<div class="box box0"></div>
<div class="box box1"></div>
<div class="box box2"></div>
<div class="box box3"></div>
<div class="box box4"></div>
<div class="box box5"></div>
<div class="box box6"></div>
<div class="box box7"></div>
</div>
Tips for your code:
In your CSS code, the wrapper element has a width property. This
causes the page and the wrapper element to have a scrollbars. So,
remove it.
You do not need to use javascript to add stickiness to the
boxes. The only CSS will do this for you. You need JavaScript only
for add the left property and shadow to the boxes.
Don’t try to use overflow: auto|scroll|hidden on the parent element
of a position:sticky element. It completely breaks the stickiness.
overflow: visible is fine. See the code snippet below.
In your JavaScript code, the flag variant value, always is true, So
the shadow class can't remove from elements.
Other notes:
If you’re wanting to use position:absolute on an element inside of
a sticky element you have to be careful. If your app is running in
an older browser that doesn’t support position:sticky, then that
sticky element won’t act like a relative positioned element. So
the absolute positioned element will skip it and look up the DOM
tree until it finds the next non-static element (absolute / relative / fixed position), defaulting to the html element if none
found. In other words, your absolute positioned element is going
to be in a way different place on the screen than you expected it to
be.
position: sticky; is supported in a lot of browsers, but not yet
in Edge. IE doesn’t matter at this point. There are many
polyfills out there if you absolutely have to have this behavior,
but they all use JavaScript. A better option is to design your app
so that sticky position is a slick addition, but the app still
functions without it.
Example:
const boxes = Array.from( document.querySelectorAll( '.box' ) ),
scroller = document.querySelector( '.scroller' ),
leftMargin = 30,
length = boxes.length - 1;
function scrollWrap() {
boxes.forEach( function( box, index ) {
let leftMarginStop = index * leftMargin;
const boxCoord = box.getBoundingClientRect();
let leftCoordPanel = boxCoord.left;
if ( leftCoordPanel <= leftMarginStop ) {
box.style.left = leftMarginStop + 'px';
if ( index < length ) boxes[ index + 1 ].classList.add( 'shadow' )
if ( index == 0 && boxes[ 1 ].getBoundingClientRect().left == box.offsetWidth ) boxes[ 1 ].classList.remove( 'shadow' )
} else {
box.style.left = 0;
if ( index < length ) boxes[ index + 1 ].classList.remove( 'shadow' )
}
} );
}
scroller.addEventListener( 'scroll', scrollWrap )
html,
body {
margin: 0;
height: 100%
}
.scroller {
height: 100%;
display: flex;
align-items: center;
overflow-x: auto;
overflow-y: hidden
}
.wrapper {
height: 100%;
display: flex
}
.box {
min-width: 630px;
height: 100%;
position: -webkit-sticky;
position: sticky;
left: 0 /* <-- become sticky once touching left edge */
}
.box1 {
min-width: 357px;
background: #1a1a1a url(https://cdn.pixabay.com/photo/2015/12/10/16/09/seamless-pattern-1086662__340.jpg)
}
.box2 {
min-width: 357px;
background: #333 url(https://cdn.pixabay.com/photo/2015/12/18/23/46/template-1099298__340.png)
}
.box3 {
min-width: 702px;
background: #4d4d4d url(https://cdn.pixabay.com/photo/2014/07/28/16/00/pattern-403769__340.png)
}
.box4 {
background: #666 url(https://cdn.pixabay.com/photo/2017/06/10/03/14/damask-2388884__340.png)
}
.box5 {
background: #808080 url(https://cdn.pixabay.com/photo/2015/12/12/17/34/seamless-pattern-1089797__340.png)
}
.box6 {
min-width: 357px;
background: #999 url(https://cdn.pixabay.com/photo/2016/03/06/16/23/background-1240686__340.png)
}
.box7 {
background: #b3b3b3 url(https://cdn.pixabay.com/photo/2018/04/24/05/00/backdrop-3346304__340.png)
}
.box8 {
background: #ccc url(https://cdn.pixabay.com/photo/2016/04/01/09/03/floral-1299131__340.png)
}
.shadow {
box-shadow: -10px 0px 40px rgba(0, 0, 0, 1);
}
<div class="scroller">
<div class="wrapper">
<div class="box box1"></div>
<div class="box box2"></div>
<div class="box box3"></div>
<div class="box box4"></div>
<div class="box box5"></div>
<div class="box box6"></div>
<div class="box box7"></div>
<div class="box box8"></div>
</div>
</div>
About your updated code:
the following line in your jS code:
const leftSideOfNextItem = box.nextElementSibling.getBoundingClientRect().left;
causes an error. Because, when index become 8, box.nextElementSibling can't retrieve any element. So you can change it to this:
const leftSideOfNextItem = ( index < boxes.length - 1 ) ? box.nextElementSibling.getBoundingClientRect().left : 0;
Also at the end of your JS code, the following code snippet:
if (index[4] && leftSideOfCurrent < leftMarginStop) {
console.log("helo");
}
must change to:
// when panel 5 reach left margin, left margin change from 60 to 30 to all panels
if (index == 4 && leftSideOfCurrent <= leftMarginStop) {
console.log("helo");
leftMargin = 30
}
Also you must change const leftMargin = 60; to var leftMargin = 60;
Updated code:
const boxes = Array.from(document.querySelectorAll(".box"));
const wrapper = document.querySelector(".wrapper");
var leftMargin = 60; //px
function scrollWrap(e) {
let scrollCoord = wrapper.scrollLeft; // horizontal scroll value
boxes.forEach((box, index) => {
let leftMarginStop = (index) * leftMargin; // calculation for left margin stop (60, 120, 180,...)
const boxCoord = box.getBoundingClientRect();
const leftSideOfCurrent = boxCoord.left; // coordinarion of left side of panel
const rightSideOfCurrent = boxCoord.right; // coordinarion of right side of panel
const leftSideOfNextItem = ( index < boxes.length - 1 ) ? box.nextElementSibling.getBoundingClientRect().left: 0; // coordinarion of left side of NEXT panel
box.style.position = "sticky";
box.style.left = `${leftMarginStop}px`;
// controll shadow of first element
scrollCoord > 0 ? boxes[1].classList.add("shadow") : boxes[1].classList.remove("shadow");
// controll shadow of all 0+ elements
if (leftSideOfCurrent <= leftMarginStop) { // if left side of pannel is less than margin 60, 120, 180,...
box.nextElementSibling.classList.add("shadow");
}
// controll removal of shadow of all 0+ elements
if (leftSideOfNextItem === rightSideOfCurrent) {
box.nextElementSibling.classList.remove("shadow");
}
// when panel 5 reach left margin, left margin change from 60 to 30 to all panels
if (index == 4 && leftSideOfCurrent <= leftMarginStop) {
console.log("helo");
leftMargin = 30
}
});
}
wrapper.addEventListener("scroll", scrollWrap);
body {
margin: 0;
padding: 0;
}
.wrapper, .box0, .box1, .box2, .box3, .box4, .box5, .box6, .box7 {
position: sticky;
height: 750px;
z-index: 1;
}
.wrapper {
width: 1442px;
border-right: 1px solid #f2f2f2;
border-bottom: 1px solid #f2f2f2;
display: flex;
overflow: scroll;
}
.wrapper .box0 {
min-width: 357px;
background-color: #1a1a1a;
}
.wrapper .box1 {
min-width: 357px;
background-color: #333;
}
.wrapper .box2 {
min-width: 702px;
background-color: #4d4d4d;
}
.wrapper .box3 {
min-width: 630px;
background-color: #666;
}
.wrapper .box4 {
min-width: 630px;
background-color: #808080;
}
.wrapper .box5 {
min-width: 357px;
background-color: #999;
}
.wrapper .box6 {
min-width: 630px;
background-color: #b3b3b3;
}
.wrapper .box7 {
min-width: 630px;
background-color: #ccc;
}
.shadow {
box-shadow: -4px 0px 40px rgba(0, 0, 0, 1.2);
-webkit-transition: box-shadow 0.2s cubic-bezier(0.4,-0.01, 0, 0.98);
-moz-transition: box-shadow 0.2s cubic-bezier(0.4,-0.01, 0, 0.98);
-o-transition: box-shadow 0.2s cubic-bezier(0.4,-0.01, 0, 0.98);
transition: box-shadow 0.2s cubic-bezier(0.4,-0.01, 0, 0.98);
}
/* To make the console visible. */
.box0 {
height: 700px;
)
<div class="wrapper">
<div class="box box0"></div>
<div class="box box1"></div>
<div class="box box2"></div>
<div class="box box3"></div>
<div class="box box4"></div>
<div class="box box5"></div>
<div class="box box6"></div>
<div class="box box7"></div>
</div>
This was helpful. I know for error but could not fix it. I have set let leftMargin = 60; i use let instead var.
I am working on the margins, if the 5th panel reaches the left margin the margin of all panels get 30px. I did it also for reverse:
if (index > 4 && leftSideOfCurrent <= leftMarginStop) {
leftMargin = 30;
} else if (index < 5 && leftSideOfCurrent > leftMarginStop) {
leftMargin = 60;
}
But now when 5th panel reaches left margin, the panels less than 5 get EACH transitioned seperately instead of all, but when the 5th element is no longer in left margin, all gets transitioned at same time. Why is it like that? I do not understand. Can you explain please?

Why is this animation not uniform?

I have a circle that expands and contracts, but there is a glitch at about 10px - 20px. Look carefully and you will see it "twitch".
It's as if the the circle has some alloted space and then "breaks" out of it.
https://jsfiddle.net/nj2u9bhy/4/
$A.Class.create('test',{
Name: 'Animator',
E: {
timer: '#timer'
},
init: function(){
this.animate();
},
animate: function(){
var s = this.E.timer.style;
var step = 2;
var state = 'up';
$A.setInterval(function(){
$A.log(step);
s.height = s.width = step + 'px';
s.borderRadius = step/2 + 'px';
if(state === 'up') {
step += 2;
}
if(state === 'down') {
step -= 2;
}
if(step === 2) {
state = 'up';
}
if(step === 42){
state = 'down';
}
}, 200);
}
});
I tried explicitly giving it space here:
https://jsfiddle.net/nj2u9bhy/5/
but same effect.
That is because it is an inline block element which vertical aligns to bottom so give it vertical align top solve the issue, or change it to a block element.
Updated fiddle
#timer{
position: relative;
top: 20px;
left: 20px;
display: inline-block;
width: 32px;
height: 32px;
vertical-align: top;
background-color: black;
border-radius: 16px;
}
And it can be easily done using CSS animation which will give a smoother transition (note that CSS animations are not supported in IE 9 and earlier)
#timer{
position: relative;
display: inline-block;
width: 0;
height: 0;
vertical-align: top;
background-color: black;
border-radius: 50%;
animation: zoom 3s linear infinite;
}
#keyframes zoom {
0% {width: 0; height: 0;}
50% {width: 32px; height: 32px;}
100% {width: 0; height: 0;}
}
<div id="timer">
</div>

Categories