requestAnimationFrame is not triggering the function supplied to it - javascript

I implemented a infinite loop animation using setInterval. I now like to change the implementation to requestAnimationFrame() so that I will have performance which I am after. For some reasons, requestAnimationFrame() does not call the function supplied to it.
My code looks like this;
var index = 0;
var $btn = $('.btn');
function btnBlinkRun() {
if (index < 2) {
index = index + 1;
} else {
index = 0;
}
$('#ani--scaleinout').removeAttr('id');
$($btn[index]).attr('id', 'ani--scaleinout');
window.requestAnimationFrame(btnBlinkRun);
}
btnBlinkRun();
.btn{
width: 30px;
height: 30px;
background: blue;
border-radius: 100%;
margin-bottom: 10px;
}
#ani--scaleinout {
animation: zoominout 1s ease-in;
}
#keyframes zoominout {
50% {
transform: scale(1.4);
}
100% {
transform: scale(1);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="btn" id="ani--scaleinout"></div>
<div class="btn"></div>
<div class="btn"></div>
</div>

It looks like what's going on is you are firing requestAnimationFrame multiple times per second. Your css animation has a duration of 1s. But you are removing the attribute every x ms.
It is triggering, it's just happening so fast you can't see it. To demonstrate change your call to window.requestAnimationFrame to use a setTimeout and you'll notice the animation:
setTimeout(function() {
window.requestAnimationFrame(btnBlinkRun);
}, 1000);
Not saying this is a preferred solution, but explaining why this is happening.

It executes alright. But it does not do what you want it to, i presume.
Animation frame fires on every single rending frame (e.g. 60fps) and not on CSS animation keyframes.
The animationend event is your friend here.
var index = 0;
var buttons = document.querySelectorAll('.btn');
function btnBlinkRun() {
if (index < 2) {
index = index + 1;
} else {
index = 0;
}
const element = document.querySelector('#ani--scaleinout');
element.id = null;
buttons[index].id = 'ani--scaleinout';
buttons[index].addEventListener("animationend", btnBlinkRun, { once: true });
}
btnBlinkRun();
.btn{
width: 30px;
height: 30px;
background: blue;
border-radius: 100%;
margin-bottom: 10px;
}
#ani--scaleinout {
animation: zoominout 1s ease-in;
}
#keyframes zoominout {
50% {
transform: scale(1.4);
}
100% {
transform: scale(1);
}
}
<div>
<div class="btn" id="ani--scaleinout"></div>
<div class="btn"></div>
<div class="btn"></div>
</div>

Related

CSS transition creating problem in JavaScript? [duplicate]

Consider such div:
<div id="someid"></div>
And it's style:
#someid {
transition: background-color 10s ease;
background-color: #FF0000;
height: 100px;
width: 100px;
}
#someid:hover {
background-color: #FFFFFF;
}
I want to have a possibility to detect state (currently animating or not) of #someid via JS and/or end animation if that's possible. I've tried a thing from this answer:
document.querySelector("#someid").style.transition = "none";
but it didn't work for currently animating element.
The point is I need to detect whether element is animating now and if so, wait for animation to end or end it immediately, otherwise do nothing
I've already found transitionend event, but using it I can't detect whether element is animating at the moment.
You can listen to transition event and remove it on demand:
const el = document.getElementById('transition');
let isAnimating = false;
el.addEventListener('transitionstart', function() {
isAnimating = true;
});
el.addEventListener('transitionend', () => {
isAnimating = false;
});
el.addEventListener('transitioncancel', () => {
isAnimating = false;
});
function removeTransition(checkIfRunning) {
if (checkIfRunning && !isAnimating) {
return;
}
el.style.transition = "none";
}
#transition {
width: 100px;
height: 100px;
background: rgba(255, 0, 0, 1);
transition-property: transform background;
transition-duration: 2s;
transition-delay: 1s;
}
#transition:hover {
transform: rotate(90deg);
background: rgba(255, 0, 0, 0);
}
<div id="transition">Hello World</div>
<br />
<button onclick="removeTransition(false)">Remove Transition</button>
<br />
<br />
<button onclick="removeTransition(true)">Remove Transition on if running</button>

How to retrigger function (translate animation )

My animation function only runs once. I've tried removing and adding classes, as well as running a animationend function to create a retrigger. But still no luck. Any vanilla JS ideas?
CSS:
#element {
width: 10px;
height: 10px;
animation: "";
#keyframes movedown {
100% {
transform: translateY(10px);
}
}
JS:
btn_button.onclick = () => {
element.style.animation = "movedown 10s";
};
HTML:
<div id="element"></div>
You can use setTimeout to set element.style.animation to "". Then, you can add animation name again upon button click.
let btn = document.querySelector("#btn");
btn.onclick = () => {
element.style.animation = "movedown 2s";
setTimeout(() => element.style.animation = "", 2000)
};
#element {
width: 10px;
height: 10px;
background-color: red;
}
#keyframes movedown {
100% {
transform: translateY(50px);
}
}
<div id="element"></div>
<button id="btn">Trigger</button>

How I can animate this slideshow(by changing its src)?

Okay okay, so before marking this post as repeated. Let me explain to you:
I made a slideshow in javascript(Vue) and it works by changing its src in an object every time I press a button(next)
It works and all but the problem is that it doesn't get animated no matter what I do, I made a transition on them, set timeout function on it...etc and nothing even the smallest worked.
I could have made another idea which works by the position absolute but I don't want to do that because it will take a loot of time and it will be extremely buggy as position absolute ruins it. So any help on this please?
<template>
<main>
<div id="slideshow">
<figure id="pics">
<img id="slidepic" v-bind:src="pictures[count].src">
<figcaption>{{pictures[count].alt}}</figcaption>
</figure>
</div>
<p>{{count+1}}/{{pictures.length}}</p>
<div id="controls">
<div #click="move(-1)">Previous</div>
<div #click="move(1)">Next</div>
</div>
</main>
Javascript:
methods: {
move: function(num) {
let slideimg = document.querySelector("#slidepic");
slideimg.classList.add("fadeOut");
this.count += num;
if (this.count < 0) {
this.count = this.pictures.length - 1;
} else if (this.count >= this.pictures.length) {
this.count = 0;
}
setTimeout(function() {
slideimg.src = this.pictures[1].src;
}, 1000);
}
}
CSS:
#pics {
opacity: 0.5s;
transition: 0.5s;
}
#pics.fadeOut {
opacity: 1;
}
I didn't include the object(that is in data object, something in Vue) because it would be useless in this situation.
First off all it's transition: <property-name> 0.5s linear; and not transition: 0.5s;. See the transition documentation.
There is no animation for changing the src of an image (see list of animatable css properties).
To do something like this, you can stack all your images into one element and then use css animations and the transform property to create a carousel
var next = document.getElementById('next');
var prev = document.getElementById('prev');
var slideshow = document.getElementById('slideshow');
next.onclick = function() {
var lastChild = slideshow.children[slideshow.children.length - 1];
var firstChild = slideshow.children[0];
var activeEle = document.querySelector('.item.active');
var nextEle = document.querySelector('.item.next');
var prevEle = document.querySelector('.item.prev');
activeEle.classList.remove('active');
activeEle.classList.add('prev');
nextEle.classList.add('active');
nextEle.classList.remove('next');
prevEle.classList.remove('prev');
if (nextEle.nextElementSibling) {
nextEle.nextElementSibling.classList.add('next');
} else {
firstChild.classList.add('next');
}
};
prev.onclick = function() {
var lastChild = slideshow.children[slideshow.children.length - 1];
var activeEle = document.querySelector('.item.active');
var nextEle = document.querySelector('.item.next');
var prevEle = document.querySelector('.item.prev');
// Move the .active class to the previous element
activeEle.classList.remove('active');
activeEle.classList.add('next');
prevEle.classList.add('active');
prevEle.classList.remove('prev');
nextEle.classList.remove('next');
if (prevEle.nextElementSibling) {
prevEle.nextElementSibling.classList.add('prev');
} else {
lastChild.classList.add('prev');
}
};
#slideshow {
width: 100px;
height: 100px;
overflow: hidden;
position: relative;
}
.item {
width: 100%;
height: 100%;
color: white;
background-color: blue;
position: absolute;
/*display: none;*/
top: 0;
left: 0;
z-index: -100;
transition: translateX(-100%);
transition: transform .5s ease-in-out;
opacity: 0;
}
.active {
opacity: 1;
display: block;
z-index: 1;
transform: translateX(0);
}
.next {
transform: translateX(200%);
z-index: 1;
}
.prev {
transform: translateX(-100%);
opacity: 1;
z-index: 1;
}
<div id="slideshow">
<div class="item active">1</div>
<div class="item next">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item prev">7</div>
</div>
<button type="button" id="prev">Prev</button><button type="button" id="next">Next</button>
As you mention you want to build a slideshow on Vue JS, and because jQuery on top of Vue is not recommended, I suggest that you try Vueper Slides, available on NPM. Unless it is for a learning purpose.
I have created two solutions.
First of all. You've a typo.
#pics {
opacity: 0.5s; // <--- remove "s"
transition: 0.5s; // <--- and forgot the property-name (all, opacity ...)
}
#pics.fadeOut {
opacity: 1;
}
I commented all lines I've changed.
Solution
<template>
<main>
<div id="slideshow">
<!--
I recommend to you ref inestad of querySelector.
https://vuejs.org/v2/api/#ref
I've used the v-bind shorthand.
-->
<figure id="pics1" ref="pics1">
<img id="slidepic" :src="pictures[count].src">
<figcaption>{{pictures[count].alt}}</figcaption>
</figure>
<!--
VueJS build-in transition element.
You have to add a key attribute to detect that the content has changed.
I recommend to use this instead of your solution.
It's easier to implement, no class add/remove struggle, its a part of vue, you can add hooks etc.
https://vuejs.org/v2/guide/transitions.html
-->
<transition tag="figure" name="fade" ref="pics2">
<figure id="pics2" :key="`figure-${count}`">
<img :src="pictures[count].src">
<figcaption>{{pictures[count].alt}}</figcaption>
</figure>
</transition>
</div>
<p>{{count+1}}/{{pictures.length}}</p>
<div id="controls">
<div #click="move(-1)">Previous</div>
<div #click="move(1)">Next</div>
</div>
</main>
</template>
<script>
export default {
name: 'teams',
data() {
return {
count: 0,
pictures: [
{
src: 'https://picsum.photos/200/300',
alt: 'test'
},
{
src: 'https://picsum.photos/200/400',
alt: 'test2'
}
]
};
},
methods: {
// instead of move: function(num) {} you can also write move() {}
move(num) {
this.count += num;
if (this.count < 0) {
this.count = this.pictures.length - 1;
} else if (this.count >= this.pictures.length) {
this.count = 0;
}
}
},
// Watch "count" changes and add or remove classes
// you can also add this to your "move" method
watch: {
count() {
// access the reference
const element = this.$refs.pics1;
element.classList.add('fadeOut');
element.classList.remove('fadeIn');
setTimeout(() => {
element.classList.remove('fadeOut');
element.classList.add('fadeIn');
}, 500); // same duration as css transition
}
}
};
</script>
<style scoped lang="scss">
#pics1 {
opacity: 1;
transition: opacity 0.5s;
}
#pics1.fadeIn {
opacity: 1;
}
#pics1.fadeOut {
opacity: 0;
}
// All classes for <transition>
// There are all automatically used by vue
.fade-enter-active {
transition: opacity 0.5s;
}
.fade-leave {
display: none;
}
.fade-enter,
.fade-leave-to {
opacity: 0;
}
</style>

How to animate endless loop using jquery?

I have been trying using jquery animate to do a running text. But I can't seems to get it run in an endless loop. It always runs one time only..
/* js: */
$(document).ready(function(){
function scroll() {
$('.scroll').animate({
right: $(document).width()
}, 8000, scroll);
}
scroll();
});
/* css: */
.scroll {
position: absolute;
right: -200px;
width: 200px;
}
<!-- html: -->
<div class="scroll">This text be scrollin'!</div>
This is the demo:
https://jsfiddle.net/y9hvr9fa/1/
Do you guys know how to fix it?
So this is what I did:
Precalculate $(document).width() as if a horizontal scroll appears, the width will change in the next iteration
Remove the width you have set for scroll so that the width is only as long as the content - and you would have to give white-space:nowrap to keep the text in a line.
In the animate use the width of the scroll text using $('.scroll').outerWidth()
See demo below and update fiddle here
$(document).ready(function() {
// initialize
var $width = $(document).width();
var $scrollWidth = $('.scroll').outerWidth();
$('.scroll').css({'right': -$scrollWidth + 'px'});
// animate
function scroll() {
$('.scroll').animate({
right: $width
}, 8000, 'linear', function() {
$('.scroll').css({'right': -$scrollWidth + 'px'});
scroll();
});
}
scroll();
});
body {
overflow: hidden;
}
.scroll {
position: absolute;
white-space: nowrap;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scroll">This text be scrollin'!</div>
Let me know your feedback on this, thanks!
CSS Alternative:
Alternatively you could use a CSS transition like in this CodePen:
https://codepen.io/jamesbarnett/pen/kfmKa
More advanced:
$(document).ready(function(){
var scroller = $('#scroller'); // scroller $(Element)
var scrollerWidth = scroller.width(); // get its width
var scrollerXPos = window.innerWidth; // init position from window width
var speed = 1.5;
scroller.css('left', scrollerXPos); // set initial position
function moveLeft() {
if(scrollerXPos <= 0 - scrollerWidth) scrollerXPos = window.innerWidth;
scrollerXPos -= speed;
scroller.css('left', scrollerXPos);
window.requestAnimationFrame(moveLeft);
}
window.requestAnimationFrame(moveLeft);
});
.scroll {
display: block;
position: absolute;
overflow: visible;
white-space: nowrap;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="scroller" class="scroll">This text be scrollin'!</div>
Dirty solution (my original answer):
In this example this would be a quick fix:
The text is running to the left without ever stopping. Here you will tell the text to always start at that position. (After the time has run up - meaning not necessarily just when it has left the screen)
$(document).ready(function(){
function scroll() {
$('.scroll').css('right', '-200px').animate({
right: $(document).width()
}, 8000, scroll);
}
scroll();
});
I have been trying using jquery animate to do a running text.
You know that the <marquee> HTML element works, right?
Which means you don't need CSS, Javascript or jQuery.
Pure HTML Solution:
<marquee>This text be scrollin'!</marquee>
The <marquee> element includes a large number of optional declarative attributes which control the behaviour of the scrolling text:
behavior
bgcolor
direction
height
hspace
loop
scrollamount
scrolldelay
truespeed
vspace
width
Further Reading:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/marquee
Note 1:
The resource above correctly notes that:
This feature is no longer recommended. Though some browsers might
still support it, it may have already been removed from the relevant
web standards, may be in the process of being dropped, or may only be
kept for compatibility purposes.
Note 2
The same resource also recommends:
see the compatibility table at the bottom of this page to guide your decision
And... a cursory look at that compatibility table shows that the <marquee> element is as browser-compatible as the most established, most browser-compatible elements which exist today.
I hope it is useful :)
function start() {
new mq('latest-news');
mqRotate(mqr);
}
window.onload = start;
function objWidth(obj) {
if (obj.offsetWidth) return obj.offsetWidth;
if (obj.clip) return obj.clip.width;
return 0;
}
var mqr = [];
function mq(id) {
this.mqo = document.getElementById(id);
var wid = objWidth(this.mqo.getElementsByTagName("span")[0]) + 5;
var fulwid = objWidth(this.mqo);
var txt = this.mqo.getElementsByTagName("span")[0].innerHTML;
this.mqo.innerHTML = "";
var heit = this.mqo.style.height;
this.mqo.onmouseout = function () {
mqRotate(mqr);
};
this.mqo.onmouseover = function () {
clearTimeout(mqr[0].TO);
};
this.mqo.ary = [];
var maxw = Math.ceil(fulwid / wid) + 1;
for (var i = 0; i < maxw; i++) {
this.mqo.ary[i] = document.createElement("div");
this.mqo.ary[i].innerHTML = txt;
this.mqo.ary[i].style.position = "absolute";
this.mqo.ary[i].style.left = wid * i + "px";
this.mqo.ary[i].style.width = wid + "px";
this.mqo.ary[i].style.height = heit;
this.mqo.appendChild(this.mqo.ary[i]);
}
mqr.push(this.mqo);
}
function mqRotate(mqr) {
if (!mqr) return;
for (var j = mqr.length - 1; j > -1; j--) {
maxa = mqr[j].ary.length;
for (var i = 0; i < maxa; i++) {
var x = mqr[j].ary[i].style;
x.left = parseInt(x.left, 10) - 1 + "px";
}
var y = mqr[j].ary[0].style;
if (parseInt(y.left, 10) + parseInt(y.width, 10) < 0) {
var z = mqr[j].ary.shift();
z.style.left = parseInt(z.style.left) + parseInt(z.style.width) * maxa + "px";
mqr[j].ary.push(z);
}
}
mqr[0].TO = setTimeout("mqRotate(mqr)", 20);
}
.marquee {
position: relative;
overflow: hidden;
text-align: center;
margin: 0 auto;
width: 100%;
height: 30px;
display: flex;
align-items: center;
white-space: nowrap;
}
#latest-news {
line-height: 32px;
a {
color: #555555;
font-size: 13px;
font-weight: 300;
&:hover {
color: #000000;
}
}
span {
font-size: 18px;
position: relative;
top: 4px;
color: #999999;
}
}
<div id="latest-news" class="marquee">
<span style="white-space:nowrap;">
<span> •</span>
one Lorem ipsum dolor sit amet
<span> •</span>
two In publishing and graphic design
<span> •</span>
three Lorem ipsum is a placeholder text commonly
</span>
</div>
How is this?
.scroll {
height: 50px;
overflow: hidden;
position: relative;
}
.scroll p{
position: absolute;
width: 100%;
height: 100%;
margin: 0;
line-height: 50px;
text-align: center;
-moz-transform:translateX(100%);
-webkit-transform:translateX(100%);
transform:translateX(100%);
-moz-animation: scroll 8s linear infinite;
-webkit-animation: scroll 8s linear infinite;
animation: scroll 8s linear infinite;
}
#-moz-keyframes scroll {
0% { -moz-transform: translateX(100%); }
100% { -moz-transform: translateX(-100%); }
}
#-webkit-keyframes scroll {
0% { -webkit-transform: translateX(100%); }
100% { -webkit-transform: translateX(-100%); }
}
#keyframes scroll {
0% {
-moz-transform: translateX(100%);
-webkit-transform: translateX(100%);
transform: translateX(100%);
}
100% {
-moz-transform: translateX(-100%);
-webkit-transform: translateX(-100%);
transform: translateX(-100%);
}
}
<div class="scroll"><p>This text be scrollin'!</p></div>

setInterval is not adding .addClass

I have a CSS marquee that displays values from a DB. After x minutes it refreshes and new data is pulled. The colors change based on their numerical value (if x < 50000 make it red ...etc).
My issue is once my setInterval runs the data is updated but the color classes don't get added. Any idea why? I saw this post and changed my remove/add class to a toggle but it was the same issue, the toggle wasn't being called after the initial run.
Javascript
$(document).ready(function () {
setColors();
setInterval(function () {
$('.marquee').addClass("paused");
$('.marquee').load('/Home/GetMarquee');
setColors();
$('.marquee').removeClass("paused");
}, 30000);
});
function setColors() {
$('.totalSales').each(function () {
var final = $(this).text();
//removes all the pervious classes
$(this).removeClass('ok');
$(this).removeClass('down');
$(this).removeClass('up');
if (final > 100000) {
$(this).addClass('up');
} else if (final < 50000) {
$(this).addClass('down');
} else {
$(this).addClass('ok');
}
});
}
Razor HTML
<div class="marquee">
<span>
#for (var i = 0; i < Model.tickerData.Count(); i++)
{
<span class="totalSales">
#Html.DisplayFor(x => x.tickerData[i].GroupName): #Html.DisplayFor(x => x.tickerData[i].Sales).....
</span>
}
</span>
</div>
CSS Colors
.down {
color:#AB2218;
}
.up {
color: #4F692A;
}
.ok {
color:#FABF03;
}
CSS Marquee
.marquee {
width: 800px;
margin: 0 auto;
overflow: hidden;
white-space: nowrap;
box-sizing: border-box;
background-color:black;
border: 1px black solid;
font-size:50px;
-webkit-animation: marquee 30s linear infinite alternate;
animation: marquee 30s linear infinite;
}
.paused {
animation-play-state: paused;
}
.marquee span {
display: inline-block;
text-indent: 0;
}
/* Make it move */
#keyframes marquee {
0% { text-indent: 17.5em }
100% { text-indent: -57.5em }
}
#-webkit-keyframes marquee{
0% { text-indent: 17.5em }
100% { text-indent: -57.5em }
}
.load is an async ajax function, so it doesn't block until it finishes, and the class adding and removing happens too quickly to notice. Try using the .load callback:
setInterval(function () {
$('.marquee').addClass("paused");
$('.marquee').load('/Home/GetMarquee', function() {
setColors();
$('.marquee').removeClass("paused");
});
}, 30000);

Categories