Animating a view change in iPhone and Android - javascript

Im trying to make a "UINavigationController type animation" in a Titanium project, however currently when I do the animation it does sort of a "pop back" animation where the view "comes out" of where the other one "went to". I have managed to figure out what's the value that determines where the animation ends, that is, the left property of the animation, but how do I set where the animation starts?
code to control animation:
function hideOldWindow() {
window.animate(animateOut, function(){});
}
function showNewWindow() {
var old = views[currentView];
window.remove(old);
currentView = (currentView + 1) % views.length;
var win = views[currentView];
viewControllers[currentView].onBecomeVisible();
window.add(win);
window.animate(animateIn, function(){});
}
var animateIn = Titanium.UI.createAnimation();
animateIn.left = 0;
animateIn.duration = 250;
animateIn.curve = Ti.UI.ANIMATION_CURVE_EASE_OUT;
var animateOut = Titanium.UI.createAnimation();
animateOut.left = -screenWidth + 1;
animateOut.duration = 250;
animateOut.curve = Ti.UI.ANIMATION_CURVE_EASE_OUT;

I don't know how is UINavigationController type animation, but to control where the animation starts, you have to set the left property of the view (this works for views I didn't try it on windows).
For example, to animate a view to appear, from left of the screen to the center, you can change the showNewWindow method to this:
function showNewWindow() {
var old = views[currentView];
window.remove(old);
currentView = (currentView + 1) % views.length;
var win = views[currentView];
viewControllers[currentView].onBecomeVisible();
window.add(win);
// NEW LINE
window.left = -screenWidth + 1;
window.animate(animateIn, function(){});
}
Now, window would appear from -screenWidth + 1 to left = 0.
Maybe you have to add a timeout before you animate the window to get it works.
Hope it helps

Related

React scroll animation flickery

I created a simple scroll animation to fill a vertical timeline based on the scrolling position. Link to working example
My problem is that the animation is still quite flickery, especially on mobile devices. Is there any way to make the animation more smooth? I already tried to solve this with css transition, but that didn't work.
It’s simply because you keep changing the value instantly on scroll.
I tried and made it smooth by adding a very simple css transition to App.css in the code:
* {
transition: 150ms all;
}
Once it works, you can change the selector * to the vertical line element, because we dont want it applied to all elements right, this is only for demo.
Also another approach for this. I think by not changing height value all the time but when a certain difference is met.
For example change component to this code, maybe you can try it, at least on my PC it's smooth enough
let lastValue = 0;
function App() {
useEffect(() => {
const timeline = document.querySelector(".timeline");
const timelineDraw = document.querySelector(".timeline__draw");
const bodyRect = document.body.getBoundingClientRect();
const timelineOffset = timeline.getBoundingClientRect().top - bodyRect.top;
var moveIndicator = function () {
var viewportHeight = window.innerHeight;
var hasScrolled = window.pageYOffset;
const scrolledFurther = hasScrolled - timelineOffset + viewportHeight / 4;
lastValue = lastValue === 0 ? scrolledFurther:lastValue;
if (scrolledFurther && scrolledFurther > 0) {
if (scrolledFurther > timeline.clientHeight) {
timelineDraw.style.height = `${timeline.clientHeight}px`;
return;
}
if (Math.abs(lastValue - scrolledFurther) > 2){
lastValue = scrolledFurther;
timelineDraw.style.height = `${scrolledFurther}px`;
}
return;
}
timelineDraw.style.height = "0px";
};

Javascript animation too fast

I am trying to write a javascript app which sorts dynamically created divs on a webpage, everything works and it sorts it all as it should, however I want it to animate the divs as they change position due to being sorted, I have code to do this but it moves way too fast, the only way I can see the divs move is if I put an alert in the animation code which looks like this :
function moveAnimation(to,from){
mover1.style.backgroundColor = "rgba(255,100,175,0.8)";
mover2.style.backgroundColor = "rgba(255,100,175,0.8)";
mover1.style.top = parseInt(mover1.style.top) + 10 + 'px';
mover2.style.top = parseInt(mover2.style.top) - 10 + 'px';
from = parseInt(mover1.style.top);
if(from != to && from < to)
{
//alert("TO : " + to + " From : " + from); //This makes it pause so that I can see the divs move
animate = setTimeout(moveAnimation(to,from),1000)
}
else
{
//alert("RET");
return;
}
}
And i call it simply like this :
mover1 = document.getElementById(moving1.id);
mover2 = document.getElementById(moving2.id);
var from = parseInt(in1.style.top);
var to = parseInt(in2.style.top);
moveAnimation(to,from);
When the alert is in place I can see them move frame by frame and it's doing exactly what I want, however it all happens in the blink of an eye with the divs suddenly being sorted, I would like to see them slowly move, any ideas on why my code isn't doing that?

Image Rotation using pure Javascript

PLEASE DO NOT RECOMMEND JQUERY - I AM DOING THIS EXERCISE FOR LEARNING PURPOSES.
I have implemented a JavaScript, which rotates images (_elementSlideChange) on a timer, using a set interval of 10 seconds. Also I have added a slide functionality to this, which is 7 milliseconds (_slideImage).
The image rotates automatically every 10 seconds on page load, and I have also provided next and previous buttons, which allow the user to change the images manually.
_elementSlideChange: function () {
var myString;
var myText;
for (var i = 0; i < this._imgArray.length; i++) {
var imageArr = "url(" + this._imgArray[i].src + ")";
var imageBg = this._imageHolder.style.background + "";
if (imageArr == imageBg) {
if (i == (this._imgArray.length - 1)) {
myString = "url(" + this._imgArray[0].src + ")";
myText = this._infoArray[0];
} else {
myString = "url(" + this._imgArray[(i + 1)].src + ")";
myText = this._infoArray[i + 1];
}
}
}
this._imageNextSlide.style.background = myString;
this._imageNextSlide.style.background);
this._infoElement.innerHTML = myText;
this._myTimer = setInterval(MyProject.Utils.createDelegate(this._slideImage, this), 7);
},
_slideImage: function () {
if (parseInt(this._imageHolder.style.width) >= 0 && parseInt(this._imageNextSlide.style.width) <= 450) {
this._imageHolder.style.backgroundPosition = "right";
this._imageHolder.style.width = (parseInt(this._imageHolder.style.width) - 1) + 'px';
console.log(this._imageNextSlide.style.background);
this._imageNextSlide.style.width = (parseInt(this._imageNextSlide.style.width) + 1) + 'px';
} else {
console.log("reached 0px");
if (parseInt(this._imageHolder.style.width) == 0) {
this._imageHolder.style.background = this._imageNextSlide.style.background;
this._imageHolder.style.width = 450 + 'px';
this._imageHolder === this._imageNextSlide;
this._imageHolder.className = "orginalImage";
this._imageNextSlide.style.width = 0 + "px";
this._imageNextSlide = this._dummyImageNextSlide;
this._imagesElement.appendChild(this._imageHolder);
this._imagesElement.appendChild(this._imageNextSlide);
clearInterval(this._myTimer);
}
clearInterval(this._myTimer);
clearInterval(this._elementSlideChange);
}
}
So when the user clicks on the Next arrow button, the event listener for "click" is triggered. This creates a div for the current image on display, and creates a new div, which will contain the next image. The image slide and rotation works correctly (whether it's onLoad or onClick). The issue I have is if I click the Next button, while the new div image is sliding into position, it causes it to run into an infinite loop, so the same div with the image to be displayed keeps sliding in, and the more you click the Next button, the faster the image starts to rotate.
I have tried putting a clear interval for the image rotation and slider, but I do understand my code is wrong, which causes the infinite loop of the sliding image. And I know I am close to finishing the functionality.
Can anyone please advise where I could be going wrong? Or should I try to implement the sliding DIV in another way?
Once again please don't recommend jQuery.
And thank you for your help in advance.
Kush
To solve the issue, I did re-write the entire code, where I had a next and previous button event listener.
myProject.Utils.addHandler(this._nextImageElement, "click", myProject.Utils.createDelegate(this._changeImage, this));
Both the buttons will call the same function :
_changeImage: function (e)
In this function I check to see if the function is Transition (changing images),
I declare a boolean var forward = e.target == this._nextImageElement;
Then check to see the current index if forward ? Add 1 else minus 1
this._currentImageIndex += forward ? 1 : -1;
If its at the end of the Array and forward is true, assign the this._currentImageIndex to reset to 0 or Array.length – 1 if it’s in reverse
Then call another function which gives the ‘div’ a sliding effect. In this case call it this._transitionImage(forward);
In this function, set the this._inTranstion to true. (Because the div’s are sliding in this case).
The following code solved the issue i was having.
this._slideImageElement.style.backgroundImage = "url(\"" + this._imgArray[this._currentImageIndex].src + "\")";
this._slideImageElement.style.backgroundPosition = forward ? "left" : "right";
this._slideImageElement.style.left = forward ? "auto" : "0px";
this._slideImageElement.style.right = forward ? "0px" : "auto";
The above code is very important as the object is to place the “sliding in div” Left or Right of the current Visible “div” to the user, and this is mainly dependent on if the forward variable is true or false.
var i = 0;
Then start the transition by
setInterval( function() {
this._currentImageElement.style.backgroundPosition = (forward ? -1 : 1) * (i + 1) + "px";
this._slideImageElement.style.width = (i + 1) + "px";
Notice the forward will determine if the bgPosition will go to the left if its forward as we multiple by -1 or +1,
So for example
If the user clicks NEXT BUTTON,
Forward = true
So the first thing we do is set the
this._slideImageElement.style.backgroundPosition = "left"
Then
this._slideImageElement.style.left = "auto"
this._slideImageElement.style.right = "0px"
This means when the sliding image moves in its background position is LEFT but the div is placed on the RIGHT to 0px;
then this._currentImageElement.style.backgroundPosition = -1 * (i + 1)
Which moves the position of the currentImageElement to the left by 1px,
Increase the width of the slideImage which in this case is right of the current div,
and as the current div moves to the left the sliding image starts to appear from the right. (By default set the width of slideImageElement to 0px so the div exists but isn’t visible to the user). This gives it the slide effect of moving forward new image coming from the right.
this._slideImageElement.style.width = (i + 1) + "px";
then declare it to stop when it it’s the image width. In this case it will be 500px.
if ((i = i + 2) == 500) {
In this if statement reset the currentImageElement background and the background position “right” or “left” don’t really matter as long it has been reset.
Clear the interval
Set the transition to false again
Then call a setTimeout for the function changeImage, which will continue until the slide is completed.
The following shows the reset code as this is very important to prevent repeating the same image (This solved my entire issue)
// set the current image to the "new" current image and reset it's background position
this._currentImageElement.style.backgroundImage = "url(\"" + this._imgArray[this._currentImageIndex].src + "\")";
this._currentImageElement.style.backgroundPosition = "right";
// reset the slide image width
this._slideImageElement.style.width = "0px";
// clear the transition interval and mark as not in transition
clearInterval(this._transitionInterval);
this._inTransition = false;
// setup the next image timer
this._nextImageTimeout = setTimeout(myProject.Utils.createDelegate(this._changeImage, this), 2500);
}
I have provided a thorough detail because then it easier to understand the logic of the problem, and even if your not having the same issue, this may help you fingure out any problem.
I couldn't provide a JSfiddle, as i have created my CSS using Javascript, there are different ways of doing this, but i wanted to understand the logic behind the forward and reverse, and having a timer which continuously goes forward.
It seems like you want to cancel the animation on the slide (perhaps have it fade out while the next slide animates in, cancel its animation abruptly or let it finish and ignore the button click)
What I usually do, personally, is check for the animated state (yes, I use jquery, but you should be able to test the CSS or positioning values you are using to animate in the same way) you could even add an "active" class or data type during animation to make testing easier. Global flags work, too. If there is animation, ignore the button. (For my work... Depends on your intention)
Like I said, the problem may be with button behaviour not with the animation routine. It would be useful to see how you are calling this from the button click, and what your intended results are going to be.
How about CSS3 transitions?
transition: all 1s ease 0.5s;
Simple example on JS Fiddle.
This takes care of the animation, so you just need to set the intended destination using JavaScript, i.e.
this.style.left = '100px';
Or
this.style.top = '30px';
And CSS3 transitions will smoothly slide the element.
Cross Browser Note!
The transition property may need a vendor prefix for some browsers, I am using the latest production Firefox and you don't need -moz for that. Same goes for Opera, no '-o' required. Internet Exporer 10 needs no prefix. You may need to use -webkit for Safari / Chrome, but test without first.

Fixing the animation properties

I am doing some research at the moment into creating a new maths game for primary school children where divs from 0-9 appear at random inside a container.
A question is given at the beginning. Something like, multiples of 20. The user will then have to click on the correct ones, and they will then be counted at the end and a score will be given.
I have just changed the speed in which the divs appear so that they appear for longer and more than one at a time to make the game easier for younger children.
I used "fadeIn" like so..
$('#' + id).animate({
top: newY,
left: newX
}, 'slow', function() {}).fadeIn(2000);
}
My problem is that now when I shoot the correct or incorrect number the animation is very glitchy and I cannot figure out why.
Fiddle: http://jsfiddle.net/cFKHq/6/ (See version 5 to see what it was like before)
Inside startplay(), control the concurrency when calling scramble() , I do it with a global var named window.cont, so I replaced your following call:
play = setInterval(scramble, 1800);
for this one:
play = setInterval(function() {
if (window.cont){
window.cont = false;
scramble();
}
}, 1000);
The var window.cont needs to be set globally at the start of your code, like so:
var miss = 0;
var hit = 0;
var target = $("#target");
window.cont = true;
So with window.cont you now can control that animations are executed one after another, without overlapping, like so:
$('#'+id).css({
top: newY,
left: newX
}).fadeIn(2000, function() {
setTimeout(function() {
$('#' + id).slideUp('fast');
window.cont = true;
}, 1500);
});
See working demo

problems setting css with jquery

I have created a slideshow with jquery. It clones an image in a container, moves it to the right, then slides it to the left and starts over. Here is the code:
$(document).ready(function() {
var slideshow = new main.slideshow();
slideshow.start({
path: 'images/slideshow/',
images: ['1', '2']
});
});
var main = new (function() {
this.slideshow = (function() {
var self = this;
var nextSlide, path, images, startLeft;
var fileExtension = 'jpg';
var container = $('#slideshow');
var currentSlide = container.children('img');
var timerlength = 4000;
var currentSlideIndex = 0;
this.start = function(args) {
path = args['path'];
images = args['images'];
if (typeof args['fileExtension'] !== 'undefined') fileExtension = args['fileExtension'];
container.css('overflow', 'hidden');
currentSlide.css('position', 'absolute');
startLeft = currentSlide.position();
startLeft = startLeft.left;
self.nextSlide();
};
this.nextSlide = function() {
nextSlide = currentSlide.clone();
nextSlide.css('left', (startLeft + currentSlide.width()) + 'px');
currentSlideIndex++;
if (currentSlideIndex >= images.length) currentSlideIndex = 0;
nextSlide.attr('src', path + images[currentSlideIndex] + '.' + fileExtension);
container.append(nextSlide);
setTimeout(function() {
self.slideToNext();
}, timerlength);
};
this.slideToNext = function() {
currentSlide.animate({
left: '-' + (currentSlide.width() - startLeft) + 'px'
}, 2000);
nextSlide.animate({
left: startLeft + 'px'
}, 2000, function() {
currentSlide.remove();
currentSlide = nextSlide;
self.nextSlide();
});
};
});
});
A link to see this in action can be found here:
https://dustinhendricks.com/breastfest/public_html/
The problem I'm having as you can see is that the second slide when first added to the dom, does not seem to be moved to the right when I call css('left', x);. After the first jQuery animation however, each cloned slide then seems to be able to be moved to the right with that call no problem. This leads me to believe that jquery's animate is setting something that allows for the object to be moved via css('left', x);, but what could it be changing? position is already being set to absolute.
This is why my example pages seems to take a while before the slides start sliding. Any idea how I can fix?
If your first image is not loaded yet when you call .start() such that currentslide.width() isn't correct, then it won't set the proper initial value for left upon initialization. You may need to set a .load() event handler so you know when that first slide is loaded and you can wait for it to be loaded before starting the slideshow.
When testing this, you must set the .load() handler before the .src value is set on the image object (or you may miss the load event in IE) and you should make sure you test both the cases where no images are cached and where all images are cached (as the timing of the load event can be different in both cases).

Categories

Resources