Counter Increment Exponentially - javascript

I'm trying to increment my counter every time but when the html is clicked the counter grows exponentially like +1, +2, +3, +4.
$('.dates').click(function(){
$('#output').html(function(i, val) { return val*1+1 });
});
HTML:
<div id="output">0</div>
Heart Animation Code:
var rand = Math.floor(Math.random() * 100 + 1);
var flows = ["flowOne", "flowTwo", "flowThree"];
var colors = ["colOne", "colTwo", "colThree", "colFour", "colFive", "colSix"];
var timing = (Math.random() * (1.3 - 0.3) + 1.6).toFixed(1);
// Animate Particle
$('<div class="particle part-' + rand + ' ' + colors[Math.floor(Math.random() * 6)] + '" style="font-size:' + Math.floor(Math.random() * (30 - 22) + 22) + 'px;"><i class="fa fa-heart-o"></i><i class="fa fa-heart"></i></div>').appendTo('.particle-box').css({ animation: "" + flows[Math.floor(Math.random() * 3)] + " " + timing + "s linear" });
$('.part-' + rand).show();
// Remove Particle
setTimeout(function () {
$('.part-' + rand).remove();
}, timing * 1000 - 100);
Why is it incrementing exponentially?
How do I make it increment by 1 every time? Like 0, 1, 2, 3, 4

Most likely, you are registering a new click event listener every time you click.
Please check and post the code that surrounds the line $('.dates').click(...).
Make sure this line is called only once in your code, and not again later.

May be it is considering it as string. Use parseInt to parse the value as an integer instead of using String Concatenation:
$('.dates').click(function() {
$('#output').html(function(i, val) {
return parseInt(val, 10) + 1;
});
});
Working snippet:
$('.dates').click(function() {
$('#output').html(function(i, val) {
return parseInt(val, 10) + 1;
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click
<div id="output">0</div>

Related

How to show a word from the specified result

I'm having trouble displaying words on the screen. I want result 1,2,3,4,5,6,7,8,9,10 then it is Fail and 11,12,13,14,15,16,17,18 it is true but I am not expert family. Someone help me please? Sorry if it's hard for you to understand because I use google translate. Here is my code
let images = ["dice-01.svg",
"dice-02.svg",
"dice-03.svg",
"dice-04.svg",
"dice-05.svg",
"dice-06.svg"];
let dice = document.querySelectorAll("img");
function roll(){
dice.forEach(function(die){
die.classList.add("shake");
});
setTimeout(function(){
dice.forEach(function(die){
die.classList.remove("shake");
});
let dieOneValue = Math.floor(Math.random()*6);
let dieTwoValue = Math.floor(Math.random()*6);
let dieTthreeValue = Math.floor(Math.random()*6);
console.log(dieOneValue,dieTwoValue);
document.querySelector("#die-1").setAttribute("src", images[dieOneValue]);
document.querySelector("#die-2").setAttribute("src", images[dieTwoValue]);
document.querySelector("#die-3").setAttribute("src", images[dieTthreeValue]);
document.querySelector("#total").innerHTML = "Your roll is " + ( (dieOneValue +1) + (dieTwoValue + 1) + (dieTthreeValue + 1) );
},
1000
);
}
roll();
<div id="die-1"></div>
<div id="die-2"></div>
<div id="die-3"></div>
<div id="total"></div>
I'd suggest creating an array rollResults to contain the results of rolling each die.
We can then get the total score, using Array.reduce() to add the roll results together.
We would then output the individual die rolls along with the total and whether the roll was successful (e.g. if it was > 10):
let images = [
'https://upload.wikimedia.org/wikipedia/commons/0/09/Dice-1.svg',
'https://upload.wikimedia.org/wikipedia/commons/3/34/Dice-2.svg',
'https://upload.wikimedia.org/wikipedia/commons/c/ca/Dice-3.svg',
"https://upload.wikimedia.org/wikipedia/commons/1/16/Dice-4.svg",
"https://upload.wikimedia.org/wikipedia/commons/d/dc/Dice-5.svg",
"https://upload.wikimedia.org/wikipedia/commons/1/14/Dice-6.svg"
];
let dice = document.querySelectorAll("img");
function getDieResult() {
return Math.floor(Math.random() * 6) + 1;
}
function roll(){
dice.forEach(function(die){
die.classList.add("shake");
});
setTimeout(function(){
dice.forEach(function(die){
die.classList.remove("shake");
});
let rollResults = Array.from({ length: dice.length }, (v,k) => getDieResult());
let total = rollResults.reduce((total, roll) => total + roll);
rollResults.forEach((result, idx) => {
document.querySelector(`#die-${idx+1}`).setAttribute("src", images[result - 1]);
})
const success = (total > 10) ? "True": "False"
document.querySelector("#total").innerHTML = "<br>Your roll is " + rollResults.join(", ") + "<br> Total = " + total;
document.querySelector("#total").innerHTML += "<br>Success = " + success;
},
250
);
}
roll();
<img id='die-1' width='50px'>
<img id='die-2' width='50px'>
<img id='die-3' width='50px'>
<div id='total'></div>
<br>
<button onclick='roll()'>Roll the dice!</button>
You can simply sum up the values and use that
const dieSum = (dieOneValue +1) + (dieTwoValue + 1) + (dieTthreeValue + 1);
let result = (dieSum > 10); // true if <=10 or false if >=11
you can instead use this result in order to put whatever you want in the UI
document.querySelector("#total").innerHTML = dieSum > 10 ? "Pass" : "Fail"
As per the image it appears (& hence assumed) that the objective is to show each of the individual die-roll. Instead, the numbers are getting added and rendered.
Please replace this:
document.querySelector("#total").innerHTML = "Your roll is " + ( (dieOneValue +1) + (dieTwoValue + 1) + (dieTthreeValue + 1) );
With this:
document.querySelector("#total").innerHTML = "Your roll is " + (dieOneValue +1) + ', ' + (dieTwoValue + 1) + ', ' + (dieTthreeValue + 1);
Or, as suggested by DBS in comment below, we may use Template Strings like this:
document.querySelector("#total").innerHTML = `Your roll is $(dieOneValue +1), $(dieTwoValue + 1), $(dieTthreeValue + 1)`;
Either of the above methods would introduce a , ('comma') between each die-roll result. If 'comma' is not desired, you may use space.
Also: in case the objective is to display 'fail' if the total is 1, 2, ...10 and 'true' if the total is 11, 12, ... 18, then try this:
document.querySelector("#total").innerHTML = `Your roll is ${(dieOneValue + dieTwoValue + dieTthreeValue + 3) < 11 ? 'fail' : 'true'}`;

Round number to two decimals

I'm trying to use Math.round for the total to show only two decimals, but it doesn't work as intended. What am I doing wrong?
$(document).ready(function() {
var totalPrice = 0;
$('.food').click(function() {
var $frm = $(this).parent();
var toAdd = $frm.children(".productInput").val();
var addPrice = parseFloat($frm.children(".priceInput").val());
var addAmount = parseFloat($frm.children(".amountInput").val());
if ($('.priceInput').val() == '') {
alert('Price can not be left blank');
};
if ($('.amountInput').val() == '') {
alert('Amount can not be left blank');
} else {
var div = $("<div>");
div.append("<p class='amount'>" + addAmount + "</p>", "<p class='product'> " + toAdd + " </p>", "<p class='price'>" + addPrice + "</p>", "<p class='delete'>" + "X" + "</p>");
$frm.parent().children(".messages").append(div);
totalPrice += addAmount * addPrice;
$(".totalPrice").text("Total Price: $" + totalPrice);
}
console.log(addAmount);
console.log(addPrice);
});
$(document).on("click", ".delete", function() {
/* var subAmount = parseFloat($(this).siblings(".amount").text());
var subPrice = parseFloat($(this).siblings(".price").text());
totalPrice -= subAmount * subPrice;
$(".totalPrice").text("Total Price: $" + totalPrice);*/
$(this).closest("div").remove();
console.log(subPrice);
console.log(subAmount);
});
$(document).on("mouseover", ".delete", function() {
var hoverAmount = parseFloat($(this).siblings(".amount").text());
var hoverPrice = parseFloat($(this).siblings(".price").text());
totalPrice -= hoverAmount * hoverPrice;
Math.round(totalPrice * 100) / 100
$(".totalPrice").text("Total Price: $" + totalPrice);
$(this).closest("div").fadeTo("fast", 0.4);
});
$(document).on("mouseout", ".delete", function() {
var subAmount = parseFloat($(this).siblings(".amount").text());
var subPrice = parseFloat($(this).siblings(".price").text());
totalPrice += subAmount * subPrice;
Math.round(totalPrice * 100) / 100
$(".totalPrice").text("Total Price: $" + totalPrice);
$(this).closest("div").fadeTo("fast", 1.0);
})
});
Since I'm using float, the numbers sometimes get changed into long decimals instead of the exact amount. I'm trying to prevent this by using Math.round. If anyone have another solution to the problem that would be appreciated too.
Use Number.prototype.toFixed() with 2 as argument, in order to round it to two decimals.
Just, remember that the returned value is a String:
let totalPrice = 4.655555;
totalPrice = totalPrice.toFixed(2);
console.log(totalPrice); // "4.66"
console.log(typeof totalPrice); // string
If you want to return a number, use Number(totalPrice.toFixed(2)) — just keep in mind that i.e: Number((7.005).toFixed(2)) will return 7 (without the decimal part)
If you work with currency it is better to use fixed point numbers for precision. There is no fixed-point number type in javascript, so consider using external libraries.
E.g. Big.js or bignumber.js

Restart CSS3 animation after it's stopped

I try to implement a CSS3 list menu with animation on each item. On page load, this is an hidden menu and the animation starts on click on the button with "#trigger-overlay" ID. There's a cross to close the menu and I would like to start again the animation on new click on the button with "#trigger-overlay" ID. I think there's a piece of code missing, probably something to do with style.webkitAnimationPlayState but I don't know how. Any help ?
Here's my code :
$( "#trigger-overlay" ).click(function() {
$("ul#menu-main-menu li").each(function (i) {
$(this).attr("style", "-webkit-animation-delay:" + i * 300 + "ms;"
+ "-moz-animation-delay:" + i * 300 + "ms;"
+ "-o-animation-delay:" + i * 300 + "ms;"
+ "animation-delay:" + i * 300 + "ms;");
if (i == $("ul#menu-main-menu li").size() -1) {
$("ul#menu-main-menu").addClass("play")
}
});
You could use the transitionend event handler:
function addAnimation($elem) {
$elem.attr("style", "-webkit-animation-delay:" + i * 300 + "ms;"
+ "-moz-animation-delay:" + i * 300 + "ms;"
+ "-o-animation-delay:" + i * 300 + "ms;"
+ "animation-delay:" + i * 300 + "ms;");
}
$( "#trigger-overlay" ).click(function() {
$("ul#menu-main-menu li").each(function (i) {
addAnimation($(this));
if (i == $("ul#menu-main-menu li").size() -1) {
$("ul#menu-main-menu").addClass("play")
}
$(this).off('transitionend').on('transitionend', function() {
addAnimation($(this));
});
});
});

How to combine two Javascript functions on the same object

I'm stuck trying to get random colour overlay on the pictures on this site.
http://www.reportageborsen.se/reportageborsen/wordpress
The Javascript I'm trying to combine are:
$(function() {
$('.media-box .mask').each(function() {
var hue = 'rgb(' + (Math.floor((256 - 199) * Math.random()) + 200) + ',' + (Math.floor((256 - 199) * Math.random()) + 200) + ',' + (Math.floor((256 - 199) * Math.random()) + 200) + ')';
$(this).css("background-color", hue);
});
});
///and///
$('.media-box').hover(function() {
$(this).find('.mask').stop(true, true).fadeIn();
}, function() {
$(this).find('.mask').stop(true, true).fadeOut();
});​
Is it possible to just get them together in some way?
Best Regards
Fortes
if you are looking to combine two functions in one, you may try this:
var getRandomInRange = function(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
$('.media-box').each(function() {
var mediaBox = $(this);
var mask = mediaBox.find('.mask');
var hue = 'rgb(' + getRandomInRange(200, 255) + ',' + getRandomInRange(200, 255) + ',' + getRandomInRange(200, 255) + ')';
mask.css("background-color", hue);
mediaBox.hover(function() {
mask.stop(true, true).fadeIn();
}, function() {
mask.stop(true, true).fadeOut();
});
});
Note, that I also moved random number generator to separate function, just for clarity. Let me know if this worked.

Button image change on a timer

In my project I have a page which contains 5 image buttons laying horizantally.
When the page loads image on the Button1 should change(remaining 4 buttons remains same).
After 3 seconds Button1 comes back to its original image and image on Button2 will change.
After 3 seconds Button2 comes back to its original image and image on Button3 will change.
And so on..
But After the Button5 is done , It should come back to the Button1 image again.
This should go on in a continuous loop.
Here is my code.But its not working I don't know the reason why its not working.
any help will be appreciated.
Here is my code
$(document).ready(function (){
BeginRotation();
});
function BeginRotation() {
rotateButton(0);
}
function rotateButton(buttonIndex) {
var previousIndex = (buttonIndex + 4) % 5;
var previousCurrentClass = 'main-nav-button' + (previousIndex + 1) + '-on';
var previousNewClass = 'main-nav-button' + (previousIndex + 1);
var currentClass = 'main-nav-button' + (buttonIndex + 1);
var newClass = 'main-nav-button' + (buttonIndex + 1) + '-on';
// alert('Previous Current Class: ' + previousCurrentClass + '\nPrevious New Class: ' + previousNewClass + '\nCurrent Class: ' + currentClass + '\nNew Class: ' + newClass);
$('.' + currentClass).removeClass(currentClass).addClass(newClass);
$('.' + previousCurrentClass).removeClass(previousCurrentClass).addClass(previousNewClass);
window.setTimeout(rotateButton((buttonIndex + 1) % 5), 3000);
}
One thing that is incorrect for sure
window.setTimeout(rotateButton((buttonIndex + 1) % 5), 3000);
It should be
window.setTimeout("rotateButton(" + ((buttonIndex + 1) % 5) + ")", 3000);
I didn't test this code, but something like this should work:
jQuery(function($){
var $btns = $('a.btn');
var index = 0;
setInterval(function() {
$btns.removeClass('rotateThis');
$btns[index].addClass('rotateThis');
index = (index + 1 >= $btns.size()) ? 0 : index + 1;
}, 3000);
});
$('a.btn') being whatever selector works to grab your image buttons of course.

Categories

Resources