How can I fix this parallax animation? - javascript

I'm new to web development.
I'm doing this animation with a sprite that allows you to move the image when the user scrolls or up. The problem is that the image shakes when I scroll. How can I fix this bug?
`
var rotator = $('#rotator');
var container = $(document);
var viewport = $(window);
var images = 10;
var imageHeight = 5930 / images;
var scrollHeight = container.height();
var position = images/scrollHeight;
viewport.scroll(function(event) {
rotator.css('background-position', (-position) + 'px 0');
if(position < 5930) {
position = position + imageHeight;
if (position >= 5930) {
position = 0;
}
} else {
position = 660;
}
});
`

Related

Dynamic bottom value based on element position in browser

I am attempting to adapt this JS solution to keep a floating element above the footer of my site.
The adaption I am attempting is instead of changing the element position to absolute, I would have a dynamic bottom px value based on the position of the top of the footer, relevant to the client window.
function checkOffset() {
var onlineFloat = document.querySelector('#online-ceo');
var footer = document.querySelector('.site-footer');
function getRectTop(el){
var rect = el.getBoundingClientRect();
return rect.top;
}
if((getRectTop(onlineFloat) + document.body.scrollTop) + onlineFloat.offsetHeight >= (getRectTop(footer) + document.body.scrollTop) - 20)
var newBottom = ((getRectTop(footer) + document.body.scrollTop) - 40).toString().concat('px');
onlineFloat.style.bottom = newBottom;
if(document.body.scrollTop + window.innerHeight < (getRectTop(footer) + document.body.scrollTop))
onlineFloat.style.bottom = '20px';// restore when you scroll up
}
document.addEventListener("scroll", function(){
checkOffset();
});
The output of newBottom is currently a px value which changes on scroll, however, I am having issues setting this position to the element.
Where am I going wrong? Thanks.
With your approach (changing the bottom property), you can just calculate where the "float" should be if the footer's top position is in view (as in window.innerHeight) on scroll.
function checkOffset() {
var onlineFloat = document.querySelector('#online-ceo');
var footer = document.querySelector('.site-footer');
function getRectTop(el) {
var rect = el.getBoundingClientRect();
return rect.top;
}
var newBottom = 10 + (getRectTop(footer) < window.innerHeight ? window.innerHeight - getRectTop(footer) : 0) + 'px';
onlineFloat.style.bottom = newBottom;
}
document.addEventListener("scroll", function () {
checkOffset();
});

How to start function at specific scroll position on page?

I'm experimenting with the following code where images flip through in a canvas.
If I put the canvas, let's say at the middle of my page, I was wondering if there's a way to only make the images flip through once the viewer gets to that specific section of the page.
Right now, from the looks of it, the images start flipping through right at the top of the page, immediately when you scroll down. By the time you get to the middle of the page where the actual canvas is, the images have already finished flipping through, and it's stopped on the last frame.
I assume I have to set the function to only trigger after the user scrolls to a specific number of pixels on the Y-axis? What's the best way to do so?
Please see code below.
Thanks!
var images = new Array();
var currentLocation = 0;
var totalImages = 200;
for (var i = 1; i < totalImages; i++) {
var img = new Image;
var slug = '000' + i;
img.src = 'https://s3.amazonaws.com/clearmotion/hero/high-min/frame' + slug.slice(-3) + '-low.jpg'
images.push(img);
}
var c = document.getElementById("background");
var ctx = c.getContext("2d");
var mouseWheel = function() {
var newLocation = null;
window.addEventListener('wheel', function(e) {
e.preventDefault(); // No scroll
// update our variable at high frequency
var delta = Math.max(-1, Math.min(1, e.deltaY));
if (delta == -1) currentLocation += 1;
if (delta == 1) currentLocation -= 1;
if (currentLocation < 0) currentLocation = 0;
if (currentLocation >= (totalImages - 1)) currentLocation = (totalImages - 1);
if (newLocation === null) { // if set, we already are waiting to draw
requestAnimationFrame(setImage);
}
newLocation = currentLocation;
});
function setImage() {
if (images[newLocation]) {
ctx.fillRect(0, 0, c.width, c.height);
ctx.drawImage(images[newLocation], 0, 0, 1000, 1000);
}
newLocation = null; // so the throttler knows we can draw again
}
}
images[0].onload = function() {
ctx.fillRect(0, 0, c.width, c.height);
ctx.drawImage(images[currentLocation], 0, 0, 1000, 1000);
mouseWheel();
};
<canvas id="background" width="1000" height="1000"></canvas>
You can actually start make the images flip through once the viewer gets to that specific section of the page by using The Intersection Observer API
So you have to detect when your element in the the viewport, the canvas in this case.
To do this you have multiple ways.
By using Observer API
const element = document.querySelector("#background")
const Ob = new IntersectionObserver((entries) => {
if (entries[0].intersectionRatio <= 0) {
// Not in the viewport
} else {
// In the viewport
// You're code here
}
});
Ob.observe(element);
Or if you want to do it in you're own.
You can use this and adapt it if needed
function elementInViewport(el) {
var top = el.offsetTop
var height = el.offsetHeight;
while(el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
}
return (
top >= window.pageYOffset &&
(top + height) <= (window.pageYOffset + window.innerHeight)
);
}

Draggable jQuery Restriction

I'm trying to scroll an image by dragging my cursor. I'm using the Draggable jQuery library but I'm having a problem.
I need to determine the limit of the image so that I can block the drag to avoid showing white space.
Anyone can help me with that?
jsfiddle
<div style="width:100%;height:100%;" id="parent">
<img src="http://cdn.wallpapersafari.com/10/37/Aim58J.jpg" id="draggable"/>
$( "#draggable" ).draggable({
axis: 'x,y',
cursor: "crosshair",
});
If you need scrolling by dragging, do not use dragging. Use simple mouse move instead. Look at the example below. In this case you can scroll any content inside your container.
Hope it would help.
UPDATED:
If you need dragging of some background element, you should to drag it by mousemove and calculate visible area according to container size.
So, in few words - Drag image left till its width minus left offset is bigger than container(window) width, and so on for right, top and down offsets.
// Main script
function run() {
var $image = $('#draggable');
var $window = $(window);
var isStarted = false;
var cursorInitialPosition = {left: 0, top: 0};
var imageInitialPosition = {left: 0, top: 0};
var imageSize = {width: $image.width(), height: $image.height()};
// stop dragging
var stop = function() {
isStarted = false;
$window.unbind('mousemove', update);
};
// update image position
var update = function(event) {
// size of container (window in our case)
var containerSize = {width: $window.width(), height: $window.height()};
var left = imageInitialPosition.left + (event.pageX - cursorInitialPosition.left);
var top = imageInitialPosition.top + (event.pageY - cursorInitialPosition.top);
// don't allow dragging too left or right
if (left <= 0 && imageSize.width + left >= containerSize.width) {
$image.css('left', left);
}
// don't allow dragging too top or down
if (top <= 0 && imageSize.height + top >= containerSize.height) {
$image.css('top', top);
}
};
$window.mousedown(function(event){
var position = $image.position();
cursorInitialPosition.left = event.pageX;
cursorInitialPosition.top = event.pageY;
imageInitialPosition.left = position.left;
imageInitialPosition.top = position.top;
$(window).mousemove(update);
});
$window.mouseout(stop);
$window.mouseup(stop);
}
$(function(){
// wait for image loading because we need it size
var image = new Image;
image.onload = run;
image.src = "http://cdn.wallpapersafari.com/10/37/Aim58J.jpg";
});
https://jsfiddle.net/2hxz49bj/5/

Auto scrolling to element in scrollable div

I have 5 elements that are within a div larger than the screen (on a mobile phone).
I want the user to be able to click on one of the elements and have that element scroll to the centre of the screen.
I've tried writing this with jQuery myself, but I can't seem to get the logic quite right. I've got it kind of moving but the element selected doesn't go to the centre of the screen.
Here's a Fiddle of what I have do far: http://jsfiddle.net/geQ64/1/
Here's the JS from the fiddle also:
$(window).on('load', function() {
$('.tab-3').trigger('click');
var width = $(window).width();
if (width < 651) {
$('.ul-wrap').scrollLeft( $('.tab-3').offset().left );
}
});
$('.single-tabs').on('click', function() {
var offset = $('.tabs').width();
offset = offset/5;
var center = offset/2;
var tab = $(this).data('tab');
$('.tabs-content').hide();
$('.tab'+ tab +'').show();
var width = $(window).width();
if (width > 650) {
var arrow = tab*20-12;
$('.arrow-up').css('margin-left', '' + arrow + '%');
} else {
tab = tab - 1;
var position = offset * tab - center;
$('.ul-wrap').scrollLeft(position);
}
});
Found a fix, here's the JS is anyone needs it.
The - 55 in the var position is for an arrow that sits in the centre of the page below the elements I'm moving with this script.
$(window).on('load', function() {
$('.tab-3').trigger('click');
var width = $(window).width();
if (width < 651) {
var offset = $('.tabs').width();
offset = offset/7;
var center = offset/2;
var position = offset * 2 + center - 50;
$('.ul-wrap').animate({
scrollLeft: position
}, 200);
}
});
$('.single-tabs').on('click', function() {
var offset = $('.tabs').width();
offset = offset/7;
var center = offset/2;
var tab = $(this).data('tab');
$('.tabs-content').hide();
$('.tab'+ tab +'').show();
var width = $(window).width();
if (width > 650) {
var arrow = tab*20-12;
$('.arrow-up').css('margin-left', '' + arrow + '%');
} else {
tab = tab - 1;
var position = offset * tab + center - 50;
$('.ul-wrap').animate({
scrollLeft: position
}, 200);
}

Text parallax not working

I'm using jquery.parallax-1.1.3.js for a parallax effect. (site: http://ianlunn.co.uk/plugins/jquery-parallax/)
Problem: it works with css background-position. This works for background images but not for text in my html.
What I want: add some code to this js file that allows me to use the parallax effect on html text (H1, H2). I prefer with an ID. So a H1 would have a div around it with an ID that is connected with the parallax effect.
This is the js:
(function( $ ){
var $window = $(window);
var windowHeight = $window.height();
$window.resize(function () {
windowHeight = $window.height();
});
$.fn.parallax = function(xpos, speedFactor, outerHeight) {
var $this = $(this);
var getHeight;
var firstTop;
var paddingTop = 0;
//get the starting position of each element to have parallax applied to it
$this.each(function(){
firstTop = $this.offset().top;
});
if (outerHeight) {
getHeight = function(jqo) {
return jqo.outerHeight(true);
};
} else {
getHeight = function(jqo) {
return jqo.height();
};
}
// setup defaults if arguments aren't specified
if (arguments.length < 1 || xpos === null) xpos = "50%";
if (arguments.length < 2 || speedFactor === null) speedFactor = 0.1;
if (arguments.length < 3 || outerHeight === null) outerHeight = true;
// function to be called whenever the window is scrolled or resized
function update(){
var pos = $window.scrollTop();
$this.each(function(){
var $element = $(this);
var top = $element.offset().top;
var height = getHeight($element);
// Check if totally above or totally below viewport
if (top + height < pos || top > pos + windowHeight) {
return;
}
$this.css('backgroundPosition', xpos + " " + Math.round((firstTop - pos) * speedFactor) + "px");
});
}
$window.bind('scroll', update).resize(update);
update();
};
})(jQuery);
This is how to call the js from html:
<script type="text/javascript" src="js/jquery.parallax-1.1.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//.parallax(xPosition, speedFactor, outerHeight) options:
//xPosition - Horizontal position of the element
//inertia - speed to move relative to vertical scroll. Example: 0.1 is one tenth the speed of scrolling, 2 is twice the speed of scrolling
//outerHeight (true/false) - Whether or not jQuery should use it's outerHeight option to determine when a section is in the viewport
$('#third').parallax("50%", 0.5);
})
</script>
You give a div an ID. You give this Div a background-image. You connect the ID to the parallax effect above. I want to do the same, but then with an H1.

Categories

Resources