I've got the following code:
var tot = 0;
var prices = {
"Price1:": 37152.32,
"Price2:": 54023,
"Price3:": 37261.75
};
var animationDuration = 2000; // Must be lower than carousel rotation
function animatePrices() {
var dur = animationDuration / Object.keys(prices).length;
for (var key in prices) {
tot += prices[key];
$({
p: 0
}).animate({
p: tot
}, {
duration: dur,
easing: 'linear',
step: function(now) {
document.getElementById("total").textContent = now.toFixed(2);
document.getElementById("what-for").textContent = key + " $" + prices[key];
}
});
}
}
window.onload = function() {
animatePrices();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$<span id="total"></span>
<br>
<span id="what-for"></span>
But as you can see, in the what-for span it shows Price3. But I want it to loop through the prices as the price goes up.
Ex:
When now is 37100 then what-for is Price1.
When now is 40000 then what-for is Price2.
When now is 100000 then what-for Price3.
What am I doing wrong?
The problem in you code is that it was calling animate inside a loop. That is messing up your the variable logic. You can use something like the following. I am using recursive call on animation end here.
var tot = 0;
var prices = {
"Price1:": 37152.32,
"Price2:": 54023,
"Price3:": 37261.75
};
var pricesArray = Object.keys(prices);
var animationDuration = 20000; // Must be lower than carousel rotation
var dur = animationDuration / pricesArray.length;
function animatePrices() {
key = pricesArray.shift();
start = tot;
tot += prices[key];
if(!key)
return false;
$({
p: start
}).animate({
p: tot
}, {
duration: dur,
easing: 'linear',
step: function(now) {
$("#total").text(now.toFixed(2));
$("#what-for").text(key + " $" + prices[key]);
},
done: animatePrices
});
}
window.onload = animatePrices;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$<span id="total"></span>
<br>
<span id="what-for"></span>
If you like, added a ratio for each animation in Rejith R Krishnan code.
I changed the object associated array though, to :
var prices = [
37152.32,
54023,
37261.75
];
and the ratios :
var ratios=[];
for(var i = 0; i < prices.length; i++){
ratios[i]=prices[i]/total;
}
https://jsfiddle.net/a6k9w9k7/
Related
I am working with a code that seems to be displaying incorrectly. In my slider I have mulitple products that are displayed. When the script runs it should grab the retail price from each of the products.
Currently, it is only grabbing the retail price of the first product. Some of the sliders will display the retail price without the strike through as well.
Any suggestions could help, and I appreciate it.
<script type="text/javascript">
var ajax_load = " ";
var loadMagaziner = "/spotlite-deals/";
$("#SpotliteDeals .slider-block .ProductList").html(ajax_load).load(loadMagaziner + " .ProductList li", function(){
var $window = jQuery(window),
flexslider = { vars:{} };
// tiny helper function to add breakpoints
function getGridSize() {
return (window.innerWidth < 601) ? 1:
(window.innerWidth < 900) ? 1 : 1;
}
// check grid size on resize event
$window.resize(function() {
var gridSize = getGridSize();
flexslider.vars.minItems = gridSize;
flexslider.vars.maxItems = gridSize;
});
jQuery('#SpotliteDeals .BlockContent .slider-block').flexslider({
animation: "slide",
//selector: 'ul.ProductList > li',
slideshow: false,
itemWidth: 285,
controlNav: true,
minItems: 1, // use function to pull in initial value
maxItems: 1 // use function to pull in initial value
});
var rprice = jQuery(this).find('.p-price .RetailPriceValue').html();
var sprice = jQuery(this).find('.p-price .SalePrice').html();
if(rprice && sprice ){
var newrp = rprice.replace('$','');
var newsp = sprice.replace('$','');
var newds = Math.round(((newrp-newsp)/newrp)*100);
jQuery(this).find('.p-price .RetailPriceValue').append().html('Price: <strike>' + rprice + '</strike> (' + newds + '% off)' );
jQuery(this).find('.deal-tag').css('display','block');
} else {
jQuery(this).find('.deal-tag').css('opacity','0');
}
});
</script>
I am currently building a website and want to fade several words at certain interval and certain fading time with infinite loop. This is exactly what I'm trying to achieve:
I've come up with this but don't know how to extend the time each word is displayed independently of fading time, so that it looks like on gif.
var text = ['fade1', 'fade2', 'fade3'];
var counter = 0;
var elem = document.getElementById("fade");
function change() {
jQuery(elem).fadeTo(1400, 0, function() {
this.innerHTML = text[counter];
counter = ++counter % text.length;
jQuery(this).fadeTo(1400, 1, change)
})
}
change()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Text <span id="fade"></span></p>
You can use jQuery.delay to pause the code for a certain number of milliseconds before moving to the next one:
var timeOnEachText = 2000; // Milliseconds to spend on each before moving to next
var text = ['fade1', 'fade2', 'fade3'];
var counter = 0;
var elem = document.getElementById("fade");
function change() {
jQuery(elem).delay(timeOnEachText).fadeTo(1400, 0, function() {
this.innerHTML = text[counter];
counter = ++counter % text.length;
jQuery(this).fadeTo(1400, 1, change)
})
}
change()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Text <span id="fade"></span></p>
If you just want to change the interval, you could convert your text array to an array-object and add some values to it, like this:
var text = [
{
text: 'fade1',
fadeIn: 1000,
fadeOut: 500,
timeout: 100,
},
{
text: 'fade2',
fadeIn: 1100,
fadeOut: 1500,
timeout: 1000,
},
{
text: 'fade3',
fadeIn: 500,
fadeOut: 300,
timeout: 3000,
}
];
var counter = 0;
var fadeTimeout = 0;
var elem = document.getElementById("fade");
function change() {
var currentTextItem = text[counter];
setTimeout( () => {
jQuery(elem).fadeTo(currentTextItem.fadeIn, 0, function() {
this.innerHTML = currentTextItem.text;
counter = ++counter % text.length;
jQuery(this).fadeTo(currentTextItem.fadeOut, 1, change)
});
// Set new timeout because in this set up the next item
// controls the timeout of the previous one.
fadeTimeout = currentTextItem.timeout;
}, fadeTimeout );
}
change()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Text <span id="fade">initial text</span></p>
I don't know if it'll work for you but have you thought about using #keyframes and just hiding showing the images at different intervals? If you know what the data is before hand and the number of images, you can set up key frames and it'll display much nicer.
I want to change jquery animate function, to a function which would let me control everything manualy. Currently code increases multiple numbers with delay. Here's the code (https://jsfiddle.net/6mrLv1ma/8/):
var ammount = 10;
var duration = 0.5;
var delay = (1-duration)/ammount; // 0.05
curDelay = 0;
for(var i=0;i<ammount;i++) {
$( "#container" ).append("<div id='output"+i+"'>0</div>");
setTimeout(
(function(i) {
return function() {
animate(i, duration);
}
})(i, duration),curDelay*1000);
curDelay += delay;
}
function animate(i, duration){
$({value: 0}).animate({value: 1}, {
duration: duration*1000,
step: function() {
var placement = "output"+i;
document.getElementById(placement).innerHTML = this.value;
}
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"></div>
Here's graph how it's working:
So if currentProc = 0.2, the output should be something like this:
0.3
0.16
0.07
0
0
0
0
0
0
0
I already started but need help with the formula(https://jsfiddle.net/18kd85hn/1/):
var ammount = 10;
var duration = 0.5;
var delay = (1-duration)/ammount; // 0.05
function myFunction(currentProc){ // currentProc value 0 - 1
var values = [];
for(var i = 0; i<ammount;i++){
var currentPos = i*delay; // formula
document.getElementById("output").innerHTML += "<br>"+currentPos;
}
}
myFunction(0.2)
<div id="output">output:</div>
Got it (https://jsfiddle.net/18kd85hn/7/)
var value = 1-(i*delay+duration-currentProc)/duration;
if (value<0){value =0}
if (value>1){value =1}
And replaced jquery animate - https://jsfiddle.net/18kd85hn/8/
the problem it's about a roulette that spins every 1 min,
Problem : When I switch from one tab to another on google chrome or any other navigators, the script stops running and the roulette stops (and I need to go back to the tab again in order to make the script work)
image roulette = animation of game
//<![CDATA[
var myRoll = {
nbr : [14, 1, 13, 2, 12, 3, 11, 0, 4, 10, 5, 9, 6, 8 ,7],
initRoll : function(){
var Ccolor;
var nbrCtn = $(".nbr-ctn");
for(j = 0; j < 6 ; j++){
for(i = 0; i < this.nbr.length; i++){
Ccolor = "";
if(this.nbr[i] === 0 ){
Ccolor = "nbr-green";
}else if(this.nbr[i] > 7){
Ccolor = "nbr-black";
}else{
Ccolor = "nbr-red";
}
var elem = '<div class="nbr '+ Ccolor +'" >'+ this.nbr[i] +'</div>';
nbrCtn.append(elem);
}
}
},
lastResult : function(n){
Ccolor = "";
if(n === 0 ){
Ccolor = "nbr nbr-green";
}else if(n > 7){
Ccolor = "nbr nbr-black";
}else{
Ccolor = "nbr nbr-red";
}
var nbrResult = $(".lastResult > div").length;
if(nbrResult === 5 ){
$(".lastResult div:first-child").remove();
}
var elem = '<div class="circle '+ Ccolor +'" >'+ n +'</div>';
$(".lastResult").append(elem);
},
rollAnimation : function(offset, n){
var prog = $(".progress-line");
if(offset){
prog.width("100%");
var nbrCtn = $(".nbr-ctn");
nbrCtn.css("left" , "0px");
nbrCtn.animate({left: "-"+ offset +".5px"}, 6000, 'easeInOutQuint', function(){
myRoll.lastResult(n);
myRoll.countDown();
});
}
},
getRandomInt : function(min, max){
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
},
startRoll : function(n){
var nbrCtn = $(".nbr-ctn");
var gAnim = $("#game-animation");
var idx = this.nbr.indexOf(n) + this.nbr.length * 4;
var elmWidth = nbrCtn.find(".nbr").width();
var offset = idx * elmWidth - (gAnim.width() / 2);
offset = this.getRandomInt(offset + 5, offset + elmWidth - 5);
this.rollAnimation(offset, n);
},
countDown : function(){
var prog = $(".progress-line");
var gameStatus = $(".rolling > span");
prog.animate({width : "0px"}, {
duration: 30000,
step: function(now){
var rt = (now*3) / 100;
gameStatus.html("Closing in " + rt.toFixed(2));
},
complete: function(){
// when the progress bar be end
gameStatus.html("Rolling ...");
myRoll.startRoll(myRoll.getRandomInt(0, 14));
},
easing: "linear"
});
}
};
window.onload = function(){
myRoll.initRoll();
myRoll.countDown();
};
//]]>
For this you need to implement things in following way (this is just way out).
Basic concept behind bellow code is calculate lag between tab switch and set current state accordingly.
var prevTime,curTime;
var rate = 500; //(miliseconds) you can set it.
function update()
{
var diffTime = curTime - prevTime;
if (diffTime >= rate)
{
//check if difference is more than step value then calculate
//current state accordingly. so you will always be updated as you calculating lags.
// e.g. diffTime = 1500;
// you will need to jump Math.floor(diffTime/rate) which is 3.
// calculate current state.
//your code....
prevTime = curTime;
}
requestAnimationFrame(update);
}
I'm trying to create div boxes step by step and animate them for several times when a button is pressed. I have a running code, and everything is going well. It goes right to the endhost, then it goes left again to its original place. This is mainly what I do, and also the demo is found here: http://jsfiddle.net/54hqm/3/
Now I want to happen after each click, is basically to move each DIV one after another, with a delay, instead of moving the whole stack of DIVs at once. I don't exactly know what to do. Can anyone help me with that?
$(document).ready(function () {
var count = 0;
var items = 0;
var packetNumber = 0;
var speed = 0;
$("button").click(function () {
if (count < 4) {
items = items + 1;
count++;
} else {
items = items * 2;
}
speed = $("#speed").val();
createDivs(items);
animateDivs();
});
function createDivs(divs) {
packetNumber = 1;
var left = 60;
for (var i = 0; i < divs; i++) {
var div = $("<div class='t'></div>");
div.appendTo(".packets");
$("<font class='span'>" + packetNumber + "</font>").appendTo(div);
packetNumber++;
div.css("left",left+"px");
div.hide();
left += 20;
}
}
function animateDivs() {
$(".t").each(function () {
var packet = $(this);
packet.show();
packet.animate({
left: '+=230px'
}, speed);
packet.animate({
left: '+=230px'
}, speed);
packet.animate({
top: '+=20px',
backgroundColor: "#f09090",
text: '12'
}, speed / 4, "swing", function () {
$('.span').fadeOut(100, function () {
$(this).text(function () {
return 'a' + $(this).text().replace('a', '');
}).fadeIn(100);
});
});
packet.delay(1000).animate({left:'-=230px'}, speed);
packet.animate({left:'-=230px'}, speed);
}).promise().done(function(){
$(".packets").empty();});
}
});
You can make this with 2 small modifications:
In your each() function, add the index parameter to know the index of the currently animating packet:
$(".t").each(function (index) {
Before your animate calls, insert a packet.delay() with a delay increasing with every item:
packet.delay(index * 250);
I updated your fiddle to show results.
Update: I made a second version based on your comment.