Inline Javascript stoped adding class to element - javascript

Hey I have an inline javascript code that adds a class to an element and makes it slide up in the screen. But it suddenly stopped working and I don't know why. Here's the HTMl and JS:
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 400) {
$(".converter").addClass("atcbottomactive");
} else {
$(".converter").removeClass("atcbottomactive");
}
});
.converter {
position: fixed;
height: 60px;
width: 100%;
bottom: -200;
background: #eeeeee;
transition: 1s;
z-index: 10000;
}
.ccontent {
display: inline-flex;
width: 100%;
padding: 10px 5%;
}
.atcbottomactive{
bottom:0;
transition: 1s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="background: green; height: 1500px; width: 100%;"></div>
<div class="converter"><div class="ccontent">...</div></div>
Here's the link
Thanks in advance :)

In fact, trying to use it without including JQuery gives you the error. You can solve this easily with "JavaScript" without using jQuery.
var element = document.querySelector(".converter");
window.addEventListener('scroll', function() {
var scroll = window.pageYOffset || document.documentElement.scrollTop;
if (scroll >= 400) {
element.classList.add("atcbottomactive");
} else {
element.classList.remove("atcbottomactive");
}
});
.converter {
padding: 20px 20px 200%;
background: blue;
color: white;
}
.converter.atcbottomactive {
background: green;
}
<div class="converter">
<div class="ccontent">Scroll me: 400px</div>
</div>

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.

How to make a div go over another div when clicking on it?

I have these 2 divs and when I click on div 1 I want it to go over the second div, and if I click on Div 1 again I want it to go back to its original position (I want Div 1 to increase its width so it goes over the second Div). Here is my code where I have my 2 divs next to each other. Can anyone point me in the right direction on how to accomplish this? Thanks a lot in advance!
NOTE:
- No jQuery please. I'm trying to accomplish this with javascript and css.
#parent {
display: flex;
}
#narrow {
width: 200px;
background: lightblue;
}
#wide {
flex: 1;
background: lightgreen;
}
<div id="parent">
<div id="wide">Div 1</div>
<div id="narrow">Div 2</div>
</div>
If you're willing to ditch flex, you can use a combination of float , postion:absolute and transition so that the main div "slides over" the other div
document.querySelector("#wide").onclick = toggleWidth;
function toggleWidth() {
this.classList.toggle("active");
}
#parent {
position: relative;
}
#narrow {
width: 200px;
background: lightblue;
float: right;
}
#wide {
position: absolute;
background: lightgreen;
width: calc(100% - 200px);
transition: width 2s;
}
#wide.active {
width: 100%;
opacity: 0.9;
}
<div id="parent">
<div id="wide">Div 1</div>
<div id="narrow">Div 2</div>
</div>
Note: Changing the opacity is purely optional, I've only done it to further illustrate the "slide over" effect.
Try this
#parent {
display: flex;
}
#narrow {
width: 20vw;
position: absolute;
left: calc(80vw - 10px);
background: lightblue;
z-index: 1;
margin: 0;
}
#wide {
width: calc(80vw - 10px);
background: lightgreen;
transition: all 0.3s ease-out;
}
.wider {
width: 100vw!important;
z-index: 2;
}
<div id="parent">
<div id="wide" onclick="myFunction()">Div 1</div>
<div id="narrow">Div 2</div>
</div>
<script>
function myFunction() {
var element = document.getElementById("wide");
element.classList.toggle("wider");
}
</script>
You can try it using JavaScript.
First, you prepare your CSS:
#narrow {
width: 200px;
transition: 0.32s;
overflow: hidden;
}
#wide.fullwidth ~ #narrow {
width: 0;
opacity: 0;
}
Then, the JavaScript, like this:
document.querySelector("#wide").onclick = changeDivWidth;
var wideFull = false;
function changeDivWidth () {
if (!wideFull) {
this.classList.add("fullwidth");
wideFull = true;
return; // if variable wideFull is false, function stops here
}
wideFull = false;
this.classList.remove("fullwidth");
}
Shorter approach using toggle();
document.querySelector("#wide").onclick = changeDivWidth;
function changeDivWidth () {
this.classList.toggle("fullwidth");
}
Are you looking for something like this : JSFiddle ?
JavaScript (Pure) :
function HideDivOne(){
var wide = document.getElementById("wide");
var narrow = document.getElementById("narrow");
if (wide.style.width == "70%"){
wide.style.width = "100%";
narrow.style.width = "0%";
narrow.style.opacity = "0";
}
else{
wide.style.width = "70%";
narrow.style.width = "30%";
narrow.style.opacity = "1";
}
}
CSS
#parent {
display: flex;
}
#narrow {
width: 30%;
background: lightblue;
height: 20px;
transition: 0.2s;
}
#wide {
width: 70%;
flex: 1;
background: lightgreen;
height: 20px;
transition: 0.2s;
}
HTML
<div id="parent">
<div id="wide" onclick="HideDivOne()">Div1</div>
<div id="narrow" onclick="HideDivTwo()">Div2</div>
</div>
You can change the z-index of the divs based on your desired effect. My suggestion is using jQuery. On click on div 1 add a class to the div that modify the zindex, that is, if the class is not already added, if so, remove it.

animate to right on scroll down and animate back to the left on scroll up

I'm trying to do an animation on page scroll where selected element will animate from left to right on scroll down and if back to top then animate the selected element from right to left (default position), here's what I tried
$(document).ready(function() {
$(window).scroll(function() {
var wS = $(this).scrollTop();
if (wS <= 10) {
$("#test-box").animate({
'left': 100
}, 500);
}
if (wS > 11) {
$("#test-box").animate({
'left': $('#main-container').width() - 100
}, 500);
}
});
});
#main-container {
width: 100%;
overflow: auto;
height: 500px;
}
#test-box {
background: red;
color: #ffffff;
padding: 15px;
font-size: 18px;
position: fixed;
left: 100;
top: 10;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main-container">
<div id="test-box">test</div>
</div>
As you can see, on scroll down, the test box moves as I instruct but when scroll up, it does not go to the left as default, any ideas, help please?
You can add a global variable to control the animation. See the working snippet below please, where I've commented parts of the code that I added:
$(document).ready(function() {
var animated = false; //added variable to control the animation
$(window).scroll(function() {
var wS = $(this).scrollTop();
if (animated && wS <= 10) {
$("#test-box").animate({
'left': 100
}, 500);
animated = false; //animation ended
}
if (!animated && wS > 11) {
$("#test-box").animate({
'left': $('#main-container').width() - 100
}, 500);
animated = true; //it was animated
}
});
});
#main-container {
width: 100%;
overflow: auto;
height: 500px;
}
#test-box {
background: red;
color: #ffffff;
padding: 15px;
font-size: 18px;
position: fixed;
left: 100px;
top: 10;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main-container">
<div id="test-box">test</div>
</div>
This should work, it also uses css for the animation.
$(document).ready(function() {
var box = document.querySelector('#test-box');
var stateClass = '-right';
window.addEventListener('scroll', function(event) {
box.classList.toggle(stateClass, document.body.scrollTop > 10);
});
});
#main-container {
width: 100%;
overflow: auto;
height: 2000px;
}
#test-box {
background: red;
color: #ffffff;
padding: 15px;
font-size: 18px;
position: fixed;
left: 100px;
top: 10;
transition: .5s linear;
}
#test-box.-right {
left: 100%;
transform: translateX(-100%) translateX(-100px)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main-container">
<div id="test-box">test</div>
</div>

How do I check whether the right/left edge of an element is overlapping the side of it's container?

I'm trying to display a right / left navigation arrow within a container (the arrows replace the existence of a scrollbar) when the corresponding edge of the content overlaps the container's sides.
Also, when the content is scrolled all the way to the end and can't scroll any further, the arrow should disappear.
My problem is, I'm confused as to how I write the function to check whether the element's contents are overlapping one edge or the other to hide one arrow or the other.
I started writing logic like this:
function setArrows(elem){
if (elem.scrollLeft() > 0) { //scroll position is greater than zero
// show left arrow
}
if () { //scroll position is less than zero
//show right arrow
}
}
but that doesn't seem to be the right logic. It sounded simpler in my head before I went to actually write the function.
How do I check whether the right/left edge of an element is overlapping the side of it's container?
Here's a Stack Snippet:
$('#wrapper').scroll(function(){
//check edges
});
div {
padding: 0px;
margin: 0px;
}
#wrapper {
width: 500px;
height: 100px;
background-color: blue;
overflow-x: scroll;
overflow-y:hidden;
}
#content {
width: 1000px;
height: 100px;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="wrapper">
<div id="content">
</div>
</div>
You need to check if the content width minus the scrollLeft is greater than the wrapper width. If it is show the right scroller..
Something like this
$(function() {
var content = $('#content'),
arrows = $('.arrow'),
wrapper = $('#wrapper').scroll(function() {
//check edges
// handle left arrow
if (this.scrollLeft > 0) {
arrows.filter('.left').addClass('visible');
} else {
arrows.filter('.left').removeClass('visible');
};
// handle right arrow
if (content.outerWidth() - this.scrollLeft > wrapper.width()) {
arrows.filter('.right').addClass('visible');
} else {
arrows.filter('.right').removeClass('visible');
};
});
arrows.on('click', function() {
if ($(this).is('.left')) {
wrapper[0].scrollLeft -= 100;
} else {
wrapper[0].scrollLeft += 100;
}
return false;
});
// initialize
wrapper.trigger('scroll');
});
div {
padding: 0px;
margin: 0px;
}
#wrapper {
width: 500px;
height: 100px;
background-color: blue;
overflow-x: hidden;
overflow-y: hidden;
position: relative;
}
#content {
width: 1000px;
height: 100px;
background: url('http://lorempixel.com/1000/100/abstract/2') 0 0 no-repeat;
}
#full-container {
position: relative;
display: inline-block;
}
.arrow {
position: absolute;
top: 0;
bottom: 0;
width: 40px;
background-color: black;
display: none;
z-index: 100;
cursor: pointer;
color: #fff;
text-align: center;
line-height: 100px;
}
.arrow.visible {
display: block;
}
.arrow.left {
left: 0
}
.arrow.right {
right: 0
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="full-container">
<div class="arrow left"><</div>
<div id="wrapper">
<div id="content"></div>
</div>
<div class="arrow right">></div>
</div>

Content that scrolls with page, but is inside a fixed positioned sidebar (with shadow effect)

I'm trying to develop following functionality for a sidebar. In a nutshell, Sidebar will have 100% height and will be absolutely positioned. Inside it there is content, which should scroll with the page, while sidebar is fixed. And as addition there is a shadow effect / response to show user if he can scroll down or up. So for example if there is something that can be scrolled down / up show shadow there, if not don't show shadow. I made a quick mockup, hopefully it will help you understand what happens if page is scrolled:
I made a quick jsfidle with content and sidebar, this is as far as I can get at the moment. http://jsfiddle.net/cJGVJ/3/
I assume this can't be achieved only with css and html and work cross browser, so jQuery solutions are welcome.
HTML
<div id="main"> <!-- Demo Content (Scroll down for sidebar) -->
<!-- Demo content here -->
</div>
<aside id="sidebar">
<div id="side-content-1"></div>
<div id="side-content-2"></div>
</aside>
CSS
body {
background: #f3f3f3;
margin: 0;
padding: 0;
}
#page-wrapper {
width: 90%;
margin: 0 auto;
overflow: hidden;
}
#sidebar {
width: 30%;
float: left;
background: #ffffff;
padding: 10px;
height: 100%;
position: fixed;
}
#main {
width: 60%;
float: right;
}
#side-content-1, #side-content-2 {
height: 400px;
}
#side-content-1 {
background: red;
opacity: 0.4;
}
#side-content-2 {
background: green;
opacity: 0.4;
margin-top: 10px;
}
EDIT
Bare in mind content in sidebar sums up to less than one of the page content, so once it reaches the bottom (so when bottom shadow disappears) it should stay there, while main content can be still scrolled down.
This is still a little rough, but its a start:
I went through and polished it a little more and took care of some window resizing issues.
I think this will work for you:
Updated Working Example
JS
$(window).scroll(function () {
var y = $(window).scrollTop();
var x = $(window).scrollTop() + $(window).height();
var s = $('#sidebar').height();
var o = $('#side-content-1').offset().top;
var q = $('#side-content-1').offset().top + $('#side-content-1').height();
var u = $('#side-content-2').offset().top;
if (x > s) {
$('#sidebar').css({
'position': 'fixed',
'bottom': '0',
'width': '27%'
});
$('#bottomShadow').hide();
}
if (x < s) {
$('#sidebar').css({
'position': 'static',
'width': '30%'
});
$('#bottomShadow').show();
}
if (y > o) {
$('#topShadow').show().css({
'position': 'fixed',
'top': '-2px'
});
}
if (y < o) {
$('#topShadow').hide();
}
if (y > q - 4 && y < q + 10) {
$('#topShadow').hide();
}
if (x > u - 10 && x < u + 4) {
$('#bottomShadow').hide();
}
});
var shadow = (function () {
$('#topShadow, #bottomShadow').width($('#sidebar').width());
});
$(window).resize(shadow);
$(document).ready(shadow);
CSS
body {
background: #f3f3f3;
margin: 0;
padding: 0;
}
#page-wrapper {
width: 90%;
margin: 0 auto;
overflow: hidden;
}
#sidebar {
width: 30%;
float:left;
background: #ffffff;
padding: 10px;
}
#main {
width: 60%;
float: right;
}
#side-content-1, #side-content-2 {
height: 400px;
}
#side-content-1 {
background: red;
opacity: 0.4;
}
#side-content-2 {
background: green;
opacity: 0.4;
margin-top: 10px;
}
#topShadow {
display:none;
height:2px;
box-shadow:0px 5px 4px #000;
}
#bottomShadow {
position:fixed;
bottom:-3px;
height:2px;
width:99%;
box-shadow:0px -5px 4px #000;
}
CSS Tricks website have an article on Persistent Headers where they accomplish something similar with a bit of JQuery

Categories

Resources