Simulate accumulation of DOM elements - javascript

I'm animating several image element children within a div container holder... they will gradually fall from the top to the bottom of the screen
I want to simulate accumulation... Meaning, if an image intersects another, it will lay on top of it and stop moving (picture snow falling and accumulating)
The way I thought to do this is iterate through each child image and animate its location... then loop through each sibling and check if there is an intersection... but of course this double loop provides terrible performance... Any thoughts?
function update () {
var myInterval = null;
clearInterval(myInterval);
myInterval = setInterval(function() {
$("#holder > img").each(function() {
$(this).css({top: $(this).position().top+=3});
var $el = $(this); //bind context
$el.siblings().each(function() {
if ($el.position().top >= $(this).position().top) {
log("INTERSECT");
}
});
});
}, 10);
}

Two things to consider:
It seems you are trying to make the animation yourself, step by step. It might be easier to use jQuery's .animate() instead.
No need to check for intersections when the layout engine can do that for you. Just put the images where they need to be but in a way in which they are not initially visible. For example, position: relative; and bottom: someVeryBigNumber;. Then animate them to their final place.
<div id="container">
<div id="droppableWrapper">
<div class="droppable"></div>
<div class="droppable"></div>
<div class="droppable"></div>
<div class="droppable"></div>
<div class="droppable"></div>
</div>
</div>
#container {
position: relative;
}
#droppableWrapper {
position: absolute;
bottom: 0px;
}
.droppable {
position: relative;
bottom: 1000px; /* Enough to be out of the screen */
}
var stack = new Array();
$(".droppable").each(function(){
// Note that the order of the stack
// is the inverse of the visual "stack" effect.
stack.push(new Droppable($(this)));
});
startDropping();
function startDropping(){
dropNext();
}
function dropNext(){
var droppable = stack.pop();
if(droppable){
droppable.drop().done(dropNext);
}
}
function Droppable(domElem) {
function drop(){
return domElem.animate({
bottom :"0px"
},{
duration: 1000
}).promise();
}
this.drop = drop;
}
Here's a fiddle: fiddle
And a fancier one, using jQuery UI, in case this is what you're looking for: fiddle

Related

Run a javascript function from HTML events

I'm working on a project that animate on page scroll.
This is the element I want to animate.
<h1 style="position: relative; top: 0; left: 0;"
onscroll="animateAfterPosition(200)"
data-animate-left="50px" data-animate-top="50px"
data-animate-time="0.2s">Animation on scroll</h1>
This is my JavaScript
function animateAfterPosition(scroll) {
console.log(scroll);
function(){
if (window.scrollY <= scroll) {
this.classList.add('animateAfterPosition');
} else {
this.classList.remove('animateAfterPosition');
}}
And this is my CSS
.animateAfterPosition {
transition: attr(data-animate-time);
left: attr(data-animate-left);
top: attr(data-animate-top);}
I need to run the function animateAfterPosition from the html. I expected to run the function with onscroll event, but it doesn't work. So how can I do this?
Edit
I found that css attr() is only working with the content: property and I managed to do it with JavaScript
You need to add selector to toggle class the animation. And your current css doesn't have enough height to make scrolling window. Here's an simple snippet to run your function onload, update onscroll and toggling class.
var dataAnimate = document.querySelector('[data-animate]');
function animateAfterPosition(scroll) {
dataAnimate.classList.toggle('active', window.scrollY <= scroll);
}
window.addEventListener("scroll", function() {
return animateAfterPosition(200);
});
.animateAfterPosition {
transition: attr(data-animate-time);
left: attr(data-animate-left);
top: attr(data-animate-top);
}
[data-animate] {
height: 1000px;
}
<body onload="animateAfterPosition(200)">
<h1 style="position: relative; top: 0; left: 0;"data-animate-left="50px" data-animate-top="50px" data-animate-time="0.2s" data-animate>Animation on scroll</h1>
</body>
Fiddle: https://jsfiddle.net/rafonzoo/phmg0u46/
A minimalistic solution
You can configure it using the first 4 variables in the function. I recommend adding the indicator class to the body itself and then use a selector like body.beyond-that-point h1. This way, it's possible to make several tags behave differently as the scrolling happens.
You can test it here
This version uses a fancier effect but the logic behind is the same.
https://deneskellner.com/stackoverflow-examples/62623588/index.html
<!doctype html>
<html>
<style>
body.beyond-that-point {background:silver;}
div.text {padding:75vh 0px;text-align:center;}
</style>
<body>
<div class="text">
Scroll me down and the background will change
</div>
<script>
setTimeout(function() {
var amount = 100; // how many pixels before the miracle happens
var beyondClass = 'beyond-that-point'; // this class will be added
var targetSelector = 'body'; // which element to add the class to
var checkMS = 20; // check scroll position every N milliseconds
var eClass = document.querySelector(targetSelector).classList;
setInterval(function() {
var y = window.scrollY;
var c = beyondClass;
var isBeyond = !!(y>=amount)?1:0;
if(isBeyond==1) if(!eClass.contains(c)) eClass.add(c);
if(isBeyond==0) if( eClass.contains(c)) eClass.remove(c);
},checkMS);
},1);
</script>
</body>
</html>
Note: there are better ways to check DOM readiness but for simplicity I used setTimeout here. Feel free to change it.

Pinning Elements with Debounced Scroll Event for Performance

What is the right way to smoothly pin an element according to scroll position?
I tried debouncing a scroll listener for performance but the pinning is not accurate. Even with debouncing set to 10ms it's not smooth and the element doesn't snap cleanly to its initial position.
var scrolling = false;
var stickPosY = 100;
var heights = [];
$(".element").each( function(index) {
heights[index] = $(".element[data-trigger=" + index + "]").offset().top;
});
function pin() {
if ( !$("#aside").hasClass("fixed") ) {
var stickyLeft = $("#aside").offset().left;
var stickyWidth = $("#aside").outerWidth();
var stickyTop = $("#aside").offset().top - stickPosY;
$("#aside").addClass("fixed");
$("#aside").css({"left": stickyLeft, "top": stickyTop, "width": stickyWidth});
}
}
function unpin() {
$("#aside").css({"left": "", "top": "", "width": ""});
$("#aside").removeClass("fixed")
}
$( window ).scroll( function() {
scrolling = true;
});
setInterval( function() {
if ( scrolling ) {
scrolling = false;
var y = window.scrollY;
console.log(y);
// PIN SIDEBAR
y > stickPosY ? pin() : unpin();
//TRIGGERS
for (var i=0; i < heights.length; i++) {
if (y >= heights[i]) {
$('.element[data-trigger="' + i + '"]').addClass("blue");
}
else {
$('.element[data-trigger="' + i + '"]').removeClass("blue");
}
}
}
}, 250 );
Here's my Pen
I tried to use scrollMagic for the project on a scene with a pin and additional triggers but the scrolling wasn't very smooth. So I'm trying to rebuild it with a stripped-down version and debounced listeners. Is this approach possible, or should I rather try to optimize my scrollMagic scene?
As James points out, you can just use position: sticky as one option, but that doesn't work in older browsers and its uses are limited to simpler situations in newer browsers, so I'll continue with the JS solution assuming you want to go that route.
There is a lot going on in your JS, and I think you are probably overcomplicating things, so I will give you a few basics to consider.
When you are toggling things based on scroll, either toggle inline styles or a class, but not both. I would recommend toggling a class because it allows you to have one function that can work on multiple screen sizes (i.e., you can use media queries to change the behavior of your toggled class based on screen size). Also it keeps all your styles in one place instead of having them split between your JS and your stylesheet.
Try to keep the work you're doing while scrolling as minimal as possible. For example, cache references to elements in variables outside your scroll function so you're not continually looking them up every time you scroll a pixel. Avoid loops inside scroll functions.
Using setInterval is not generally the recommended approach for increasing performance on scroll functions. All that is going to do is run a function every X amount of time, all the time, whether you're scrolling or not. What you really want to do is rate-limit your scroll function directly. That way, if you scroll a long ways real fast your function will only be called a fraction of the total times it would otherwise be called, but if you scroll a short distance slowly it will still be called a minimum number of times to keep things looking smooth, and if you don't scroll at all then you're not calling your function at all. Also, you probably want to throttle your function in this case, not debounce it.
Consider using the throttle function from Underscore.js or Lodash.js instead of inventing your own because those ones are highly performant and guaranteed to work across a wide variety of browsers.
Here is a simple example of sticking an element to the top of the screen on scroll, throttled with Lodash. I'm using a 25ms throttle, which is about the maximum amount I'd recommend for keeping things looking smooth where you won't really notice the delay in the element sticking/unsticking as you scroll past your threshold. You could go down to as little as 10ms.
$(function() {
$(window).on('scroll', _.throttle(toggleClass, 25));
const myThing = $('#my-thing');
const threshold = $('#dummy-1').height();
function toggleClass() {
const y = window.scrollY;
if (y > threshold) {
myThing.addClass('stuck')
} else {
myThing.removeClass('stuck');
}
}
});
#dummy-1 {
height: 150px;
background-color: steelblue;
}
#dummy-2 {
height: 150px;
background-color: gold;
}
#my-thing {
width: 300px;
height: 75px;
background-color: firebrick;
position: absolute;
top: 150px;
left: 0;
}
#my-thing.stuck {
position: fixed;
top: 0;
}
body {
margin: 0;
height: 2000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.0.0/lodash.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dummy-1"></div>
<div id="dummy-2"></div>
<div id="my-thing"></div>
You could try fixed or sticky CSS positioning:
#element {
position: fixed;
top: 80px;
left: 10px;
}
Position: fixed would keep the element always at 80px from the top and 10px from the left edge regardless of scroll position.
#element{
position: sticky;
top: 0;
right: 0;
left: 0;
}
This is from a project of mine. The element is a nav bar. It sits below a header bar, so when you are at the top of the page, you see the header then the nav below it, and as you scroll down, the header moves off screen but the nav sticks at the top and is always visible.

jQuery doesn't show and hide the header

I'm trying to make a header that appears at a certain place of the page.
So what I'm doing is checking the scroll to top of the page and the top offset of the element after which the header should appear. If the scrollTop is greater than offset the header is shown, otherwise it disappears.
But! When I scroll to the place, the header position is constantly switching between top: -13% and top: -12.999998%. After some time it finally shows the header but it never disappears.
What am I doing wrong?!
JSFiddle: https://jsfiddle.net/5k5s016f/
Well, i think the problem is that the .animate() functions are running constantly, causing the animations to "restart" before its ends.
It is not the most beautiful solution, but just adding a flag that controls the execution of the functions and a timeout to run the handler less frequently solves the problem.
https://jsfiddle.net/5k5s016f/2/
var visible = false;
$(window).scroll(function() {
setTimeout(function(){
var height = $(window).scrollTop();
var $page2 = $("#page2");
var offset = $page2.offset().top;
if (height > offset) {
if (visible) {
return;
}
visible = true;
$(".floating-header").show().animate({
top: 0
});
} else {
if (!visible) {
return;
}
visible = false;
$(".floating-header").animate({
top: "-13%"
});
}
}, 200)
});
The issue you are seeing is because each time a scroll event gets called animation queues up. If you wait long enough, you can see that the animation to set top to 0 actually works.
You can use the stop() function to stop all animation before attempting to run another one.
Something like this
if (height > offset) {
$(".floating-header").stop().show().animate({
top: "0"
}, 700);
} else {
$(".floating-header").stop().animate({
top: "-13%"
}, 700);
}
A couple of improvements I can suggest are
Debounce the scroll event handler
Check the current state of the header before queuing animation. i.e. do not try to hide it if it is already hidden and vice versa
Your logic is all messed up. Basically, you want to make sure that you are only animating when you absolutely need to - no more, no less. And since scroll events happen hundreds of times... constantly rapid firing as the user scrolls... you want to make sure you are doing the least amount of work possible during each scroll event. This especially means that you don't want to be querying the DOM on every scroll event if you don't have to (ps. $('selector') is a dom query). Take a look at this fiddle:
https://jsfiddle.net/5k5s016f/6/
Looks like I'm last to the party due to interruptions, but since I wrote it up I'll post the answer FWIW.
jsFiddle Demo
You need to debounce your code. Here is a simple system, but studing Ben Alman's explanation/examples is also recommended.
var $m1 = $('#m1'), $m2 = $('#m2'); //TESTING ONLY
var $win = $(window), $page2 = $("#page2"), $hdr=$(".floating-header");
var $offset = $page2.offset().top;
var hvis = false, curpos;
$win.scroll(function() {
curpos = $win.scrollTop();
$m1.html(curpos); //TESTING ONLY
$m2.html($offset);//TESTING ONLY
if ( curpos > $offset ) {
if ( !hvis ){
hvis = true;
//$m1.html(curpos);
$hdr.finish().animate({
top: "0"
}, 700);
}
} else {
if ( hvis ){
$hdr.finish().animate({
top: "-60px"
}, 700);
hvis = false;
}
}
});
html,
body {
height: 100vh;
width: 100vw;
}
#page1,
#page2,
#page3 {
height: 100%;
width: 100%;
background-color: #fff;
}
.floating-header {
position: fixed;
top: -60px;
background-color: #000;
width: 100%;
height: 60px;
}
.msg{position:fixed;bottom:10px;height:30px;width:80px;text-align:center;}
.msg{padding-top:10px;}
#m1 {left:3px; border:1px solid orange;background:wheat;}
#m2 {right:3px;border:1px solid green; background:palegreen;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<header class="floating-header">Header</header>
<div id="page1">
<p>Page1</p>
</div>
<div id="page2">
<p>Page2</p>
</div>
<div id="page3">
<p>Page3</p>
</div>
<div id="m1" class="msg"></div>
<div id="m2" class="msg"></div>

Javascript button appear animation

I have the back to top button that appears when you reach a point on the page, which is working fine, however, when it appears the text is on two lines until the box has finished the animation to appear. So, is there anyway to prevent this? What I mean by the animation is: btt.show('slow');
Code:
$(document).ready(function () {
var btt = $('.back-to-top');
btt.on('click' , function(e) {
$('html, body').animate({
scrollTop: 0
}, 500);
btt.hide('slow');
e.preventDefault();
});
$(window).on('scroll', function () {
var self = $(this),
height = self.height(),
top = self.scrollTop();
if (top > 500) {
btt.show('slow');
} else {
btt.hide('slow');
}
});
});
Example: http://codepen.io/Riggster/pen/WvNvQm
The problem is caused by animating the width of a box, I think it might be better to animate the position of it instead, but - even better - lets use CSS animations!
$(window).on('scroll', function () {
if ($(window).scrollTop() >= 500) {
$(".button").addClass('show');
} else {
$(".button").removeClass('show');
}
});
#wrapper {
width: 100%;
height: 2000px;
}
.button {
position: fixed;
bottom: 50px;
right: -100px;
/* You might still need prefixes here. Use as preferred. */
transition: right 500ms;
}
.button.show {
right: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div id="wrapper">
<div class="button">Here's my button!</div>
</div>
I've defined your button as hidden by default, by giving it a position of right: -100px. When we hit the correct scroll position, we add the class show and that triggers the animation performed by CSS and not javascript, as we have the transition property for the property right defined - that way the browser does the heavy lifting.
Toggling show/hide alters your elements width. You either have to put it in a container with display: inline
Or more ideally you might want to change show/hide to jQuery fadeIn() / fadeOut() which is more appropriate for "Back to Top" indicators.
Here is your codepen example modified with inline container:
http://codepen.io/anon/pen/MwWweY

Scroll event background change

I am trying to add a scroll event which will change the background of a div which also acts as the window background (it has 100% width and height). This is as far as I get. I am not so good at jquery. I have seen tutorials with click event listeners. but applying the same concept , like, returning scroll event as false, gets me nowhere. also I saw a tutorial on SO where the person suggest use of array. but I get pretty confused using arrays (mostly due to syntax).
I know about plugins like waypoints.js and skrollr.js which can be used but I need to change around 50-60 (for the illusion of a video being played when scrolled) ... but it wont be feasible.
here is the code im using:-
*
{
border: 2px solid black;
}
#frame
{
background: url('1.jpg') no-repeat;
height: 1000px;
width: 100%;
}
</style>
<script>
$(function(){
for ( i=0; i = $.scrolltop; i++)
{
$("#frame").attr('src', ''+i+'.jpg');
}
});
</script>
<body>
<div id="frame"></div>
</body>
Inside your for loop, you are setting the src attribute of #frame but it is a div not an img.
So, instead of this:
$("#frame").attr('src', ''+i+'.jpg');
Try this:
$("#frame").css('background-image', 'url(' + i + '.jpg)');
To bind a scroll event to a target element with jQuery:
$('#target').scroll(function() {
//do stuff here
});
To bind a scroll event to the window with jQuery:
$(window).scroll(function () {
//do stuff here
});
Here is the documentation for jQuery .scroll().
UPDATE:
If I understand right, here is a working demo on jsFiddle of what you want to achieve.
CSS:
html, body {
min-height: 1200px; /* for testing the scroll bar */
}
div#frame {
display: block;
position: fixed; /* Set this to fixed to lock that element on the position */
width: 300px;
height: 300px;
z-index: -1; /* Keep the bg frame at the bottom of other elements. */
}
Javascript:
$(document).ready(function() {
switchImage();
});
$(window).scroll(function () {
switchImage();
});
//using images from dummyimages.com for demonstration (300px by 300px)
var images = ["http://dummyimage.com/300x300/000000/fff",
"http://dummyimage.com/300x300/ffcc00/000",
"http://dummyimage.com/300x300/ff0000/000",
"http://dummyimage.com/300x300/ff00cc/000",
"http://dummyimage.com/300x300/ccff00/000"
];
//Gets a valid index from the image array using the scroll-y value as a factor.
function switchImage()
{
var sTop = $(window).scrollTop();
var index = sTop > 0 ? $(document).height() / sTop : 0;
index = Math.round(index) % images.length;
//console.log(index);
$("#frame").css('background-image', 'url(' + images[index] + ')');
}
HTML:
<div id="frame"></div>
Further Suggestions:
I suggest you change the background-image of the body, instead of the div. But, if you have to use a div for this; then you better add a resize event-istener to the window and set/update the height of that div with every resize. The reason is; height:100% does not work as expected in any browser.
I've done this before myself and if I were you I wouldn't use the image as a background, instead use a normal "img" tag prepend it to the top of your page use some css to ensure it stays in the back under all of the other elements. This way you could manipulate the size of the image to fit screen width better. I ran into a lot of issues trying to get the background to size correctly.
Html markup:
<body>
<img src="1.jpg" id="img" />
</body>
Script code:
$(function(){
var topPage = 0, count = 0;
$(window).scroll( function() {
topPage = $(document).scrollTop();
if(topPage > 200) {
// function goes here
$('img').attr('src', ++count +'.jpg');
}
});
});
I'm not totally sure if this is what you're trying to do but basically, when the window is scrolled, you assign the value of the distance to the top of the page, then you can run an if statement to see if you are a certain point. After that just simply change run the function you would like to run.
If you want to supply a range you want the image to change from do something like this, so what will happen is this will allow you to run a function only between the specificied range between 200 and 400 which is the distance from the top of the page.
$(function(){
var topPage = 0, count = 0;
$(window).scroll( function() {
topPage = $(document).scrollTop();
if(topPage > 200 && topPage < 400) {
// function goes here
$('#img').attr('src', ++count +'.jpg');
}
});
});

Categories

Resources