Changing text in page div - javascript

im trying to make something like text rotator.
When i click on About tab i want to show only about info, when i click on projects i want to delete about text and replace it with project text and same with other depending which i actually press.
I can make it to appear one under another. But that's not what i want. Hope you guys understand what i want to do.
DON'T WRITE IT FOR ME! Just please tell me where i should look for it, should i use loop?
HTML:
<main>
<div class="menuContainer">
<ul>
<li class="about" id="about">
<h2>O mnie</h2>
</li>
<li class="projects" id="projects">
<h2>Projekty</h2>
</li>
<li class="empty">
<div class="circle"></div>
</li>
<li class="technology" id="technology">
<h2>Technologie</h2>
</li>
<li class="contact" id="contact">
<h2>Kontakt</h2>
</li>
</ul>
</div>
<div class="poleDoZmiany">
<p id="doZmiany" class="zmiana">
Welcome Lorem ipsum dolor, sit amet consectetur adipisicing elit. Suscipit culpa labore temporibus fugiat eum error hic illo perspiciatis dignissimos, corporis, aut sapiente sint numquam!
</p>
</div>
<p id="Tekst1">Lorem ipsum dolor sit amet consectetur adipisicing elit. Tenetur, natus nam! Excepturi ipsam voluptates magni odio adipisci, officia consequuntur praesentium eos cumque exercitationem soluta, eveniet dolor sed reiciendis asperiores modi pariatur placeat animi, debitis ratione. Hic illo incidunt, praesentium excepturi vero perspiciatis corrupti maxime accusamus, iusto repellendus quam id. </p>
<p id="Tekst2">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Possimus sint modi quisquam autem perferendis maxime impedit sed. Doloremque, reprehenderit neque perspiciatis facere quia saepe architecto odio aspernatur, voluptas nobis blanditiis, quisquam beatae?
</p>
<p id="Tekst3">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Obcaecati, facilis. Deserunt, in.
</p>
<p id="Tekst4">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Iure fugiat sequi accusantium inventore asperiores magnam impedit sit maiores praesentium! Ea exercitationem, veritatis placeat blanditiis vitae iste, cupiditate asperiores voluptate cumque quisquam ipsam repellat accusamus debitis omnis aliquid! Iste rerum consectetur impedit porro molestias numquam. Facere eveniet at dolorum deleniti! Facilis nisi ut beatae laudantium nulla culpa amet neque inventore at minus. Reiciendis distinctio ab voluptas! Earum excepturi corporis odit?
</p>
CSS:
main {
width: 80%;
position: absolute;
left: 10%;
top: 35vh;
background: white;
-webkit-box-shadow: 0px 0px 34px 2px rgba(0,0,0,0.75);
-moz-box-shadow: 0px 0px 34px 2px rgba(0,0,0,0.75);
box-shadow: 0px 0px 34px 2px rgba(0,0,0,0.75);
}
main p {
margin-top: 90px !important;
margin: 25px;
padding: 25px;
text-align: center;
}
.media {
text-align: center;
}
.media > img {
padding: 10px;
}
p {
display: none;
}
#doZmiany {
display: block;
}
JAVASCRIPT:
let tekst1 = document.getElementById('Tekst1');
let tekst2 = document.getElementById('Tekst2');
let tekst3 = document.getElementById('Tekst3');
let tekst4 = document.getElementById('Tekst4');
var zmiana = document.getElementById('doZmiany');
const oMnie = document.getElementById('about');
const projekty = document.getElementById('projects');
oMnie.addEventListener('click', function(){
tekst1.classList.add('zmiana');
})
projekty.addEventListener('click', function(){
tekst2.classList.add('zmiana');
})

You're almost there. Keep in mind, that you need to hide all the paragraphs you don't want to show with every click. So a loop is a good idea.
And then show the one and only.
Here is a code snippet that does something like that a little different from your approach in case you get stuck. Go on with your solution!
document.getElementById('tablist').addEventListener('click', function(e){
const tabs = ['tab1', 'tab2'];
const ti = tabs.indexOf(e.target.id);
if(ti !== false){
for(let i = 0; i < tabs.length; i += 1) {
if(ti !== i){
document.getElementById(tabs[i]+'Txt').style.display = 'none';
}
}
document.getElementById(tabs[ti]+'Txt').style.display = 'block';
}
});
.hiddenText {
display: none;
}
<ul id="tablist">
<li id="tab1">tab1</li>
<li id="tab2">tab2</li>
</ul>
<p id="tab1Txt" class="hiddenText">
This is tab1Txt.
</p>
<p id="tab2Txt" class="hiddenText">
This is tab2Txt.
</p>

For your tabs, add a class called tab and for all of your content paragraphs, give them a class of tab-content.
Then create a click event for the class of tab. In the click event get the ID of what is being clicked on and use that to determine the content to be shown. First, hide ALL of tab-content paragraphs, then only show the paragraph based on the passed ID.

Related

why is this tetx not overflowing on the x axis even though I have a fixed width and the <p tag is set to display: block?

I need the text to overflow on the X axis just to reproduce some issue that I'm having on a bigger project. I leave a simple snippet, so you can tell me where I'm doing it wrong. Thanks!
.article {
background-color: rgb(236, 161, 161);
width: 20em;
}
.article p {
display: block;
}
<article class="article">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Perferendis deleniti iure quidem distinctio officia voluptates similique molestiae culpa? Perferendis, velit maiores nobis maxime aut facere eaque quis voluptas accusamus commodi.</p>
</article>
If you want the p tag to overflow on the x-axis, you simply need to tell it not to wrap using the white-space property:
article{
width: 20em;
background-color: rgb(236, 161, 161);
}
article p{
display: block;
/* Do NOT break the text onto a new line when it reaches the container bounds. */
white-space: nowrap;
}
<article>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Perferendis deleniti iure quidem distinctio officia voluptates similique molestiae culpa? Perferendis, velit maiores nobis maxime aut facere eaque quis voluptas accusamus commodi.
</p>
</article>

creating a star rating system based of an API

I have an api that will give a number of either 1-5 under "ratings" , i also have a list of 5 stars, depending on the rating these stars will either turn red or black on click of the button, red will be for each number in the Ratings . i.e a rating of 4 would turn 4 of the stars red and 1 black. so far i have the html and css created but when the button is pressed i recieve no data at all to test the button I added a basic alert and that worked. So far I have this:
DEMO:
$("#viewreview").click(function(){
$.ajax("api link").done(function(data){
$(".reviewblk").html('');
var htmlstr = '';
for(var i=0; i<data.length; i++){
var rating = parseInt(data[i]["rating"]);
var chk = ['', '', '', '', ''];
for(var j=0; j<rating && j<5;j++){
chk[j] = 'checked';
}
htmlstr += '<div class="preview"><img src="reviewicon1.jpg" alt="reviewpic" class="revImg" /><div class="stars"><p class="checked '+chk[0]+'"></p><p class="checked '+chk[1]+'"></p><p class="checked '+chk[2]+'"></p><p class="checked '+chk[3]+'"></p><p class="checked '+chk[4]+'"></p></div><h3 class="personName">'+data[i]["nickname"]+'</h3><div class="revtext"><p>'+data[i]["review"]+'</p></div></div><hr />';
}
$(".reviewblk").html(htmlstr);
});
})
.productreviews{ /*sets font*/
font-family: 'Roboto Condensed', sans-serif;
}
.preview{ /*sets padding for how the div is displayed*/
padding-left: 60px;
padding-top: 30px;
padding-bottom: 30px;
display: block;
position: relative;
}
.revImg{ /*gives images curved edges*/
border-radius: 10px;
display: inline;
}
.personName{ /*sets the person name so that it is to the right of the image and just below the stars*/
display: inline;
position: absolute;
padding-left: 30px;
padding-top: 20px;
width: 150px;
}
.stars{ /*sets stars elements to above name and to the right of the image*/
position: absolute;
width: 100px;
top: 30px;
left: 180px;
}
.revtext{ /* displays the text div so that it is to the right side of the preview box*/
display: inline;
width: 550px;
position: absolute;
right: 0;
font-size: 15px;
font-weight: 600;
top: 10px;
}
.revtext p{ /*i used word wrap to wrap the word onto the next line then used overflow to contain the overflowing text and then used text overflow so that any overflowing text would be shown as an ellipsis*/
word-wrap: break-word;
overflow: hidden;
text-overflow: ellipsis;
}
.btnreview{ /* setting the padding for the buton aswell as the color so that the text is white and the button itself is red, aswell as giving it curved edges.*/
padding: 10px 25px;
background-color: #F0191C;
color: white;
border: none;
border-radius: 10px;
}
.btnreview:hover{ /*changing the button when hovering and changing the cursor to a pointer*/
background-color: #8a130b;
cursor: pointer;
}
.btnblk{/* padding the button inside its div*/
padding: 25px;
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<article class="productreviews"> <!--list of product reviews-->
<hr />
<h1 id = "productreviewheader">Product Reviews <span class="checked">*****</span></h1>
<hr />
<div class="reviewblk">
<div class="preview">
<img src="images/robot-juice-images/reviewicon1.jpg" alt="reviewpic" class="revImg" />
<div class="stars">
<p class = "checked">*****</p>
</div>
<h3 class="personName">Great Greace!!</h3>
<div class="revtext">
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Aperiam sapiente odit porro in quam eos autem nobis quisquam reiciendis debitis magnam ipsam laboriosam iusto error quasi officia
voluptates, totam excepturi? Lorem ipsum dolor, sit amet consectetur adipisicing elit. Distinctio accusantium, neque vel, rerum illum ipsam tempore quae accusamus voluptates sequi hic
magni dolores? Eius laboriosam tempora ut molestias consectetur nobis!
</p>
</div>
</div>
<hr />
<div class="preview">
<img src="images/robot-juice-images/reviewicon1.jpg" alt="reviewpic" class="revImg" />
<div class="stars">
<p class = "checked">***<span class="unchecked">**</span></p>
</div>
<h3 class="personName">Great Greace!!</h3>
<div class="revtext">
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Aperiam sapiente odit porro in quam eos autem nobis quisquam reiciendis debitis magnam ipsam laboriosam iusto error quasi officia
voluptates, totam excepturi? Lorem ipsum dolor, sit amet consectetur adipisicing elit. Distinctio accusantium, neque vel, rerum illum ipsam tempore quae accusamus voluptates sequi hic
magni dolores? Eius laboriosam tempora ut molestias consectetur nobis!
</p>
</div>
</div>
<hr class = "separation line"/>
<div class="preview">
<img src="images/robot-juice-images/reviewicon1.jpg" alt="reviewpic" class="revImg" />
<div class="stars">
<p class = "checked">****<span class="unchecked">*</span></p>
</div>
<h3 class="personName">Great Greace!!</h3>
<div class="revtext">
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Aperiam sapiente odit porro in quam eos autem nobis quisquam reiciendis debitis magnam ipsam laboriosam iusto error quasi officia
voluptates, totam excepturi? Lorem ipsum dolor, sit amet consectetur adipisicing elit. Distinctio accusantium, neque vel, rerum illum ipsam tempore quae accusamus voluptates sequi hic
magni dolores? Eius laboriosam tempora ut molestias consectetur nobis!
</p>
</div>
</div>
<hr class = "separation line"/>
<div class="preview">
<img src="images/robot-juice-images/reviewicon2.jpg" alt="reviewpic" class="revImg" />
<div class="stars">
<p class = "checked">*****</p>
</div>
<h3 class="personName">This juice just keeps me going..</h3>
<div class="revtext">
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Aperiam sapiente odit porro in quam eos autem nobis quisquam reiciendis debitis magnam ipsam laboriosam iusto error quasi officia
voluptates, totam excepturi? Lorem ipsum dolor, sit amet consectetur adipisicing elit. Distinctio accusantium, neque vel, rerum illum ipsam tempore quae accusamus voluptates sequi hic
magni dolores? Eius laboriosam tempora ut molestias consectetur nobis!
</p>
</div>
</div>
<hr class = "separation line"/>
</div>
<div class="reviewblk">
<div class="preview">
<img src="images/robot-juice-images/reviewicon1.jpg" alt="reviewpic" class="revImg" />
<div class="stars">
<p class = "checked">*****</p>
</div>
<h3 class="personName">Great Greace!!</h3>
<div class="revtext">
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Aperiam sapiente odit porro in quam eos autem nobis quisquam reiciendis debitis magnam ipsam laboriosam iusto error quasi officia
voluptates, totam excepturi? Lorem ipsum dolor, sit amet consectetur adipisicing elit. Distinctio accusantium, neque vel, rerum illum ipsam tempore quae accusamus voluptates sequi hic
magni dolores? Eius laboriosam tempora ut molestias consectetur nobis!
</p>
</div>
</div>
<hr class = "separation line"/>
</div>
<div class="btnblk">
<button class="btnreview" id="viewreview">READ ALL REVIEWS</button>
</div>
</article>
Please consider the following.
$("#viewreview").click(function() {
$.ajax("api link").done(function(data) {
$(".reviewblk").html('');
var rating, preview, stars;
$.each(data, function(i, el) {
preview = $("<div>", {
class: "preview"
}).appendTo(".reviewblk");
$("<img>", {
src: "reviewicon1.jpg",
alt: "Review Icon",
class: "revImg"
}).appendTo(preview);
stars = $("<div>", {
class: "stars"
}).appendTo(preview);
rating = parseInt(el.rating);
for (var i = 1; i <= 5; i++) {
$("<p>", {
class: (i <= rating ? "checked" : "unchecked")
}).appendTo(stars);
}
$("<h3>", {
class: "personName"
}).html(el.nickname).appendTo(preview);
$("<div>", {
class: "revText"
}).html("<p>" + el.review + "</p>").appendTo(preview);
$("<hr>").appendTo(preview);
});
});
});
We can use jQuery to create the elements and append them as they are created. Using $.each(), we can itereate each of the items in data. WE also know there will be 5 'check' items, so we can simply create a small loop to create them. A number of them, equal to the rating will be "checked", so we can add a condition to check each one and mark it as needed.
For example, if the rating was 3, we would see:
<p class="checked"></p>
<p class="checked"></p>
<p class="checked"></p>
<p class="unchecked"></p>
<p class="unchecked"></p>
i will be 1 on the first iteration, and 1 is less than 3. On the 3rd loop, i will be 3 and will still meet the condition. When i is 4 or 5, it is no longer true so unchecked is supplied.

LERP Smooth Scrolling

I have been wanting to implement smooth scrolling in vanilla JS for some time, but could not find any adequate implementations or methods. However, I recently came across the concept of linear interpolation (LERP), which seems adequate unlike every other method.
Although content about LERP smooth scrolling seems scarce on the web, I just found two great articles (one, two) about LERP in general and an example of LERP being used for smooth scrolling on codepen.
The example, notably, seems unnecessarily complex due to a seemingly unnecessary amount of nested containers, so I created a minimal version of it shown below. The minimal version seems to be working, but I still have a few concerns and questions.
const
b = document.body,
m = document.querySelector('main'),
p = document.querySelector('p')
let
state = {
scroll: {
height: 0,
offset: 0,
speed: 0.075,
}
},
direction
document.addEventListener('DOMContentLoaded', () => {
state.scroll.height = m.getBoundingClientRect().height
b.style.height = `${Math.floor(state.scroll.height)}px`
})
b.addEventListener('wheel', (e) => {
direction = e.deltaY > 0 ? 'scrollDown' : 'scrollUp'
// renderLoop()
})
function renderLoop() {
// const
// difference = 'scrollDown' ? pageYOffset - state.scroll.offset : state.scroll.offset - pageYOffset
state.scroll.offset += Math.floor((pageYOffset - state.scroll.offset) * state.scroll.speed)
m.style.transform = `translateY(-${ state.scroll.offset }px)`
// if (difference > 20) requestAnimationFrame(renderLoop)
requestAnimationFrame(renderLoop)
}
renderLoop()
html, body {
width: 100%;
height: 100%;
margin: 0;
font-size: 48px;
}
main {
width: 100%;
position: fixed;
left: 0;
top: 0;
border: solid green 3px; box-sizing: border-box;
}
p {
width: 100%;
max-width: 500px;
position: relative;
left: 50%;
transform: translateX(-50%);
margin: 0;
border: solid red 3px; box-sizing: border-box;
}
<main>
<p>One<br>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Error soluta, quidem voluptatibus quo iusto iure adipisci, ullam quis unde dolore, nisi impedit in. Veniam, suscipit? Atque aut et incidunt aliquid. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Exercitationem labore dolore aut atque harum, quo necessitatibus molestias laborum fuga beatae explicabo laudantium asperiores doloremque optio iure, assumenda voluptate unde voluptates? Lorem ipsum dolor sit amet consectetur adipisicing elit. Amet inventore, voluptates corrupti illo impedit in. Recusandae, praesentium temporibus tempore totam cupiditate ratione maxime numquam corporis repudiandae. Veniam ullam rerum quo?</p>
<p>Two<br>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Error soluta, quidem voluptatibus quo iusto iure adipisci, ullam quis unde dolore, nisi impedit in. Veniam, suscipit? Atque aut et incidunt aliquid. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Exercitationem labore dolore aut atque harum, quo necessitatibus molestias laborum fuga beatae explicabo laudantium asperiores doloremque optio iure, assumenda voluptate unde voluptates? Lorem ipsum dolor sit amet consectetur adipisicing elit. Amet inventore, voluptates corrupti illo impedit in. Recusandae, praesentium temporibus tempore totam cupiditate ratione maxime numquam corporis repudiandae. Veniam ullam rerum quo?</p>
<p>Three<br>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Error soluta, quidem voluptatibus quo iusto iure adipisci, ullam quis unde dolore, nisi impedit in. Veniam, suscipit? Atque aut et incidunt aliquid. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Exercitationem labore dolore aut atque harum, quo necessitatibus molestias laborum fuga beatae explicabo laudantium asperiores doloremque optio iure, assumenda voluptate unde voluptates? Lorem ipsum dolor sit amet consectetur adipisicing elit. Amet inventore, voluptates corrupti illo impedit in. Recusandae, praesentium temporibus tempore totam cupiditate ratione maxime numquam corporis repudiandae. Veniam ullam rerum quo?</p>
</main>
One concern is that for some reason it breaks unless I call renderLoop from the global scope and let requestAnimationFrame run indefinitely without a killswitch, which, instinctively, does not seem like a good idea?
I am also confused by the fact that, although I am offsetting the content container via translate, there still appears to be a scrollbar that scrolls. And yet, notably, this does not appear to interfere with the effect at all. However, should LERP smooth scrolling via translate not bypass scrollbars and scrolling altogether?
Additionally, it seems as though the only purpose of setting the height of body to that of main is to make use of pageYOffset. I suspect there are better ways to approach the problem that do not involve using pageYOffset. Further, you would think that the combination of offsetting with translate and the page being scrolled would increase the rate at which the content is scrolled?
Anyways, I have just started coding again after an almost year-long absence, and I am not sure if I ever familiarized myself with requestAnimationFrame, so any information, guidance, or solutions would be greatly appreciated.
[ edit + update ]
Here is a codepen of a "working" (?) version, which can be seen below, that I created in attempt to address and solve some concerns or issues present in the version above. However, it clearly does not have the same effect due to, I believe, the offset value being a percentage instead of pixels, which was chosen in an attempt to standardize the "speed" at which it scrolls across "platforms" (i.e. devices, browsers, etc).
const
b = document.body,
m = document.querySelector('main')
let
scrollState = {
overflow: 0,
target: 0,
position: 0,
rate: 10,
speed: 0.2
}
b.addEventListener('wheel', (e) => {
scrollState.target -= scrollState.rate * (e.deltaY / 100)
if (scrollState.target > 0) scrollState.target = 0
else if (scrollState.target < -100) scrollState.target = -100
renderLoop()
})
function renderLoop() {
const
rawDiff = Math.abs(scrollState.position - scrollState.target),
direction = scrollState.position - scrollState.target < 0 ? -1 : 1,
diff = rawDiff * scrollState.speed * direction,
newPosition = scrollState.position - diff
m.style.transform = `translateY(${newPosition}%)`
scrollState.position = newPosition
if (Math.floor(rawDiff)) requestAnimationFrame(renderLoop)
}
html, body {
width: 100%;
height: 100%;
margin: 0;
font-size: 48px;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
body {
border: solid blue 4px; box-sizing: border-box;
}
main {
width: 100%;
position: fixed;
left: 0;
top: 0;
border: solid green 2px; box-sizing: border-box;
}
p {
width: 100%;
max-width: 500px;
position: relative;
left: 50%;
transform: translateX(-50%);
margin: 0;
border: solid red 2px; box-sizing: border-box;
}
<main>
<p>One<br>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Error soluta, quidem voluptatibus quo iusto iure adipisci, ullam quis unde dolore, nisi impedit in. Veniam, suscipit? Atque aut et incidunt aliquid. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Exercitationem labore dolore aut atque harum, quo necessitatibus molestias laborum fuga beatae explicabo laudantium asperiores doloremque optio iure, assumenda voluptate unde voluptates? Lorem ipsum dolor sit amet consectetur adipisicing elit. Amet inventore, voluptates corrupti illo impedit in. Recusandae, praesentium temporibus tempore totam cupiditate ratione maxime numquam corporis repudiandae. Veniam ullam rerum quo?</p>
<p>Two<br>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Error soluta, quidem voluptatibus quo iusto iure adipisci, ullam quis unde dolore, nisi impedit in. Veniam, suscipit? Atque aut et incidunt aliquid. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Exercitationem labore dolore aut atque harum, quo necessitatibus molestias laborum fuga beatae explicabo laudantium asperiores doloremque optio iure, assumenda voluptate unde voluptates? Lorem ipsum dolor sit amet consectetur adipisicing elit. Amet inventore, voluptates corrupti illo impedit in. Recusandae, praesentium temporibus tempore totam cupiditate ratione maxime numquam corporis repudiandae. Veniam ullam rerum quo?</p>
<p>Three<br>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Error soluta, quidem voluptatibus quo iusto iure adipisci, ullam quis unde dolore, nisi impedit in. Veniam, suscipit? Atque aut et incidunt aliquid. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Exercitationem labore dolore aut atque harum, quo necessitatibus molestias laborum fuga beatae explicabo laudantium asperiores doloremque optio iure, assumenda voluptate unde voluptates? Lorem ipsum dolor sit amet consectetur adipisicing elit. Amet inventore, voluptates corrupti illo impedit in. Recusandae, praesentium temporibus tempore totam cupiditate ratione maxime numquam corporis repudiandae. Veniam ullam rerum quo?</p>
</main>
#oldboy, I'm having the same issue regarding the scarcity of LERP + smooth scrolling on the web. Nevertheless, here is a slightly different approach involving smooth vertical scroll + LERP with a kill switch. It might not be perfect yet but it could be the building block to expand upon.
const slider = document.querySelector('.slider');
const track = document.querySelector('.slider-track');
let startY = 0;
let endY = 0;
let raf;
const lerp = (start,end,t) => start * (1-t) + end * t;
function update() {
startY = lerp(startY,endY,0.05);
track.style.transform = `translateY(-${startY}px)`;
raf = requestAnimationFrame(update);
if (startY.toFixed(1) === slider.scrollTop.toFixed(1)) cancelAnimationFrame(raf);
}
function move() {
endY = slider.scrollTop;
cancelAnimationFrame(raf);
raf = requestAnimationFrame(update);
}
window.addEventListener('load',update,false);
slider.addEventListener('scroll',move,false);
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.slider {
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
width: min(600px,90vw);
height: 90vh;
border: 1px solid rgba(0,0,0,0.5);
overflow-y: scroll;
}
.slider-track {
position: absolute;
width: 100%;
display: flex;
flex-direction: column;
gap: 1rem;
padding: 1rem;
}
.slider-item {
width: inherit;
height: 70vh;
border: 0.5px solid rgba(0,0,0,0.5);
display: grid;
place-items: center;
font: 900 0.85rem helvetica,sans-serif;
}
::-webkit-scrollbar { width: 1rem; }
::-webkit-scrollbar-track { border-left: 0.5px solid rgba(0,0,0,0.5); }
::-webkit-scrollbar-thumb {
border: 0.5px solid rgba(0,0,0,0.5);
border-right: none;
border-left: none;
}
<main class='slider'>
<div class='slider-track'>
<div class='slider-item'>1</div>
<div class='slider-item'>2</div>
<div class='slider-item'>3</div>
<div class='slider-item'>4</div>
<div class='slider-item'>5</div>
<div class='slider-item'>6</div>
<div class='slider-item'>7</div>
<div class='slider-item'>8</div>
<div class='slider-item'>9</div>
</div>
</main>
Overview:
create a function to run the LERP formula
const lerp = (start,end,t) => start * (1-t) + end * t;
when our project "load", do the following:
a) invoke the callback "update" & update the starting y-position aka "startY" with "lerp". "0.05" is the "easing" which can range from "0.01 to "0.99"
startY = lerp(startY,endY,0.05);
b) move our slider's "track" vertically with "translateY" + negative "startY" in pixels
track.style.transform = translateY(-${startY}px);
c) invoke "update" recursively with "requestAnimationFrame" and store it in "raf"
raf = requestAnimationFrame(update);
d) if "startY" is equal to "slider.scrollTop" to the nearest tenths then cancel "raf" (kill switch)
if (startY.toFixed(1) === slider.scrollTop.toFixed(1)) cancelAnimationFrame(raf);
lastly, whenever the "scroll" event is trigged on "slider" then:
a) invoke the callback "move" & track the current y-position aka "endY" with the "scrollTop" property on "slider"
endY = slider.scrollTop;
b) cancel "raf" (kill switch)
cancelAnimationFrame(raf);
c) invoke "update" recursively with "requestAnimationFrame"
cancelAnimationFrame(raf);
Please do drop me a comment when you improve upon this approach or your own code, I like to check'em out :)

scroll back to the top of a box on mouseout

Please, run this snippet to better understand my issue
body{
background-color: #E13241;
font-family: sans-serif;
font-weight: 300;
}
#wrapper{
width: 1130px;
margin: 100px auto;
}
.box1, .box2, .box3, .box4{
width: 230px;
height: 200px;
overflow: hidden;
float: left;
word-break: break-all;
word-spacing: -1px;
margin-left: 15px; /* or 0px */
background-color: rgba(25, 25, 25, 0.2);
padding: 15px;
transition: all 0.5s ease-in;
}
h3{
text-align: center;
}
.box1:hover, .box2:hover, .box3:hover, .box4:hover{
width: 230px;
height: 300px;
margin-top: -50px;
overflow-y: scroll;
}
::-webkit-scrollbar {width: 5px;}
::-webkit-scrollbar-track {background-color: rgba(25, 25, 25, 0.2);}
::-webkit-scrollbar-thumb {background-color: rgba(25, 25, 25, 0.2);}
<div id="wrapper">
<div class="box1">
<h3>
Title Box 1
</h3>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae, beatae! Sed assumenda cupiditate quasi officiis laborum, minima at error tempore. Voluptatibus facere iste qui? Fugit non perferendis, accusamus nostrum deleniti?
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus consequuntur laborum porro nemo, quisquam minus minima eius, deserunt similique, laboriosam dolorum tenetur et repudiandae rem fugit illum perspiciatis nam totam.
</p>
</div>
<div class="box2">
<h3>
Title Box 2
</h3>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae, beatae! Sed assumenda cupiditate quasi officiis laborum, minima at error tempore. Voluptatibus facere iste qui? Fugit non perferendis, accusamus nostrum deleniti?
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus consequuntur laborum porro nemo, quisquam minus minima eius, deserunt similique, laboriosam dolorum tenetur et repudiandae rem fugit illum perspiciatis nam totam.
</p>
</div>
<div class="box3">
<h3>
Title Box 3
</h3>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae, beatae! Sed assumenda cupiditate quasi officiis laborum, minima at error tempore. Voluptatibus facere iste qui? Fugit non perferendis, accusamus nostrum deleniti?
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus consequuntur laborum porro nemo, quisquam minus minima eius, deserunt similique, laboriosam dolorum tenetur et repudiandae rem fugit illum perspiciatis nam totam.
</p>
</div>
<div class="box4">
<h3>
Title Box 4
</h3>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae, beatae! Sed assumenda cupiditate quasi officiis laborum, minima at error tempore. Voluptatibus facere iste qui? Fugit non perferendis, accusamus nostrum deleniti?
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus consequuntur laborum porro nemo, quisquam minus minima eius, deserunt similique, laboriosam dolorum tenetur et repudiandae rem fugit illum perspiciatis nam totam.
</p>
</div>
</div>
So, I have a box within a div. When I hover it, the box gets higher and it is possible to scroll inside the box. But I can't figure a way to automatically scroll back to the top of the box when I do not hover the box anymore.
I've tried multiple things, including this js code I found in another answer :
$('#box').show();
$('#box').scrollTop(0);
$('html,body, #box').animate({scrollTop: 0}, 100);
But it's just cancelling all my css and do not work in this specific scenario.
Any idea or direction to follow ?

Sticky footer till document height greater than viewport

EDIT
Incorrectly marked as a duplicate, I marked it duplicate before I tested the answer on the referred question. It doesn't provide the exactly what I want, which is a sticky footer initially and only float to the bottom of the page when the content is larger than the viewport.
/EDIT
EDIT2
Found the answer over here, pure CSS and does exactly what I want.
/EDIT2
I want a sticky footer until the document height is greater than the viewport height, then it just should be at the end of the document.
The document is build up like this:
<body>
<div class="header">
<!-- content -->
</div>
<div class="page-content">
<!-- content -->
</div>
<div class="footer">
<!-- content -->
</div>
</body>
Fiddle
The .header has a height of 101px and .footer has a height of 173px.
.page-content has a variable height depending on the content.
What I want is for .footer to stick to the bottom of the viewport as long as .page-content doesn't contain enough content for the document to have a greater height than the viewport
I tried giving .page-content a min-hieght so it always overflows the viewport but that is just plain ugly.
Is this possible pure CSS or does Javascript/JQuery come in to play here?
Two relatively newer methods that can be used are using calc and flexbox. Both have decent support (above 90% without prefixes for calc and with prefixes for flexbox). Using them is pretty simple, especially compared to some of the older (and admittedly more supported) methods. If you really want to push support then viewport units can make them even simpler.
Method One - Calc:
CSS:
/* Only needed if not using vh in main */
html, body {
height: 100%;
}
header {
/* Needs to be static */
height: 70px;
}
footer {
/* Needs to be static */
height: 30px;
}
main {
/* Can use 100vh instead of 100% */
min-height: calc(100% - 70px - 30px);
}
HTML:
<header></header>
<main></main>
<footer></footer>
DEMO: codepen
Method Two - Flexbox:
CSS:
body {
display: flex;
flex-direction: column;
/* If using percent then html needs a height of 100% */
min-height: 100vh;
}
main {
flex: 1;
}
HTML:
<header></header>
<main></main>
<footer></footer>
DEMO: codepen
The flexbox version is nice because header and footer can be fluid. The flex: 1; in main makes sure that main will fill any remaining space left after header and footer take whatever they need. Calc's version is less powerful, requiring a static header and footer, but no prefixes. They both work fine for me, personally, with either autoprefixer or prefixfree making sure I don't have to worry about prefixes either way.
You are probably looking for something like Ryan Faits "HTML 5 Sticky Footer"
CSS:
* {
margin: 0;
}
html, body {
height: 100%;
}
.wrapper {
min-height: 100%;
height: auto !important;
height: 100%;
margin: 0 auto -4em;
}
.footer, .push {
height: 4em;
}
HTML:
<html>
<head>
<link rel="stylesheet" href="layout.css" ... />
</head>
<body>
<div class="wrapper">
<p>Your website content here.</p>
<div class="push"></div>
</div>
<div class="footer">
<p>Footer Content here</p>
</div>
</body>
</html>
In this example the footer will be 4em high. You will probably want to adjust this to your wishes by modifying the "margin"of the ".wrapper"and the "footer" "height"
You can use this css to your footer to make it at the bottom of viewport.
.footer {
position: absolute;
bottom: 0;
width: 100%;
height: 173px;
}
Check this out:
$(function () {
$(".large-content").hide();
$("a").click(function () {
$(".large-content").toggle();
fixHeight();
});
fixHeight();
});
function fixHeight() {
if ($(window).height() >= $(document).height())
$("body").addClass("fixed-footer");
else
$("body").removeClass("fixed-footer");
}
* {font-family: 'Segoe UI'; font-size: 10pt; margin: 0; padding: 0; list-style: none;}
p {margin: 0 0 10px;}
.header, .footer {text-align: center; color: #fff; background-color: #000;}
body.fixed-footer {padding-bottom: 2em;}
body.fixed-footer .footer {position: fixed; width: 100%; bottom: 0;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="header">
Header Section
</div>
<div class="page-content">
<p>Small Content</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellat aliquam error quas culpa, sapiente sunt asperiores impedit ipsa cupiditate tempore, molestias, vitae laboriosam suscipit pariatur odit? Cumque fugiat iste provident.</p>
<p>Click for large content!</p>
<div class="large-content">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas est quos officia repellat debitis molestiae incidunt et consequatur ut, dicta rerum qui delectus impedit saepe suscipit explicabo dolorem at ea?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas est quos officia repellat debitis molestiae incidunt et consequatur ut, dicta rerum qui delectus impedit saepe suscipit explicabo dolorem at ea?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas est quos officia repellat debitis molestiae incidunt et consequatur ut, dicta rerum qui delectus impedit saepe suscipit explicabo dolorem at ea?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas est quos officia repellat debitis molestiae incidunt et consequatur ut, dicta rerum qui delectus impedit saepe suscipit explicabo dolorem at ea?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas est quos officia repellat debitis molestiae incidunt et consequatur ut, dicta rerum qui delectus impedit saepe suscipit explicabo dolorem at ea?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas est quos officia repellat debitis molestiae incidunt et consequatur ut, dicta rerum qui delectus impedit saepe suscipit explicabo dolorem at ea?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas est quos officia repellat debitis molestiae incidunt et consequatur ut, dicta rerum qui delectus impedit saepe suscipit explicabo dolorem at ea?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas est quos officia repellat debitis molestiae incidunt et consequatur ut, dicta rerum qui delectus impedit saepe suscipit explicabo dolorem at ea?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas est quos officia repellat debitis molestiae incidunt et consequatur ut, dicta rerum qui delectus impedit saepe suscipit explicabo dolorem at ea?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas est quos officia repellat debitis molestiae incidunt et consequatur ut, dicta rerum qui delectus impedit saepe suscipit explicabo dolorem at ea?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas est quos officia repellat debitis molestiae incidunt et consequatur ut, dicta rerum qui delectus impedit saepe suscipit explicabo dolorem at ea?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas est quos officia repellat debitis molestiae incidunt et consequatur ut, dicta rerum qui delectus impedit saepe suscipit explicabo dolorem at ea?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas est quos officia repellat debitis molestiae incidunt et consequatur ut, dicta rerum qui delectus impedit saepe suscipit explicabo dolorem at ea?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas est quos officia repellat debitis molestiae incidunt et consequatur ut, dicta rerum qui delectus impedit saepe suscipit explicabo dolorem at ea?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas est quos officia repellat debitis molestiae incidunt et consequatur ut, dicta rerum qui delectus impedit saepe suscipit explicabo dolorem at ea?</p>
</div>
</div>
<div class="footer">
Footer Section
</div>

Categories