jquery create counter with value from div - javascript

I am trying to create a script with jquery that pulls a number from a specified div (#counter below) and adds 100 to it every second and updates the number in the div. I've tried a number of things, but nothing with the intended result. Any tips? Here is what I have currently:
<script type="text/javascript">
setInterval("counter()", 1000); // run counter function every second
function counter() {
var count = $("#counter").val(); // get value of counter div
var total = count+100; // add 100 to value of counter div
$("#counter").text(total); // update counter div
}
</script>
<div id="counter">1000</div>

A few changes:
function counter() {
var count = parseInt($('#counter').text(), 10);
$('#counter').text(count + 100);
}
setInterval(counter, 1000);
Don't pass a string to setInterval. Always pass a function.
.val() is only for <input> elements. You need to use .text() (which will return a string), so you need to parse the text into an integer with parseInt(). The 10 tells parseInt to assume base-10.

Edit - adding parseInt like others mentioned.
You're not calling counter() correctly and you should use .html() instead of val() like this:
<script type="text/javascript">
setInterval(counter, 1000); // run counter function every second
function counter() {
var count = $("#counter").html(); // get value of counter div
var total = parseInt(count)+100; // add 100 to value of counter div
$("#counter").text(total); // update counter div
}
</script>
<div id="counter">1000</div>

use
parseint($("#counter").html(), 10) // or ~~$("#counter").html()
and even
$("#counter").html(total)
instead

Try casting count to an integer?
var total = parseInt(count, 10) + 1000;
Should use jquery html() as opposed to val() unless it is a form input.
var count = $('#counter').html();
Also noticed you are not passing the function reference correctly to setInterval()
setInterval(counter, 1000);

Here is the working code: http://jsfiddle.net/FbJPY/3/
The issue is that your interval is not working, as well as you're not parsing a number from the contents of the div.
Fixes:
Interval should reference a function, not a variable, so you can type counter without quotes.
You need to parse the number from the contents of the div.
setInterval(counter, 1000); // run counter function every second
function counter() {
var count = parseInt($("#counter").text(), 10); // get value of counter div
var total = count + 100; // add 100 to value of counter div
$("#counter").text(total); // update counter div
}

Related

how can I use setInterval when I want to use while in my function?

<body onload="count()">
<p id="li1"></p>
<script>
let li1 = document.getElementById("li1");
let x = 0;
function count() {
while(x<=1000){
li1.innerHTML = x++;
}
}
setInterval(count,10)
</script>
</body>
I tried to write for instead of using while but it does not work either.
I will reformat your original post shortly. Please be careful to format your future questions properly!
You're doing a few things unnecessarily in your supplied code.
Firstly, you don't need to call count() in the body onload. The setInterval will run after DOM load and effectively handle this for you.
Secondly, because you're using setInterval to run count() every 10ms, you don't need any form of loop, whether it be for or while. The setInterval handles your looping (sort of).
Take a look at the following:
// Get the element we want to put the counter inside
let li1 = document.getElementById("li1");
// Init a variable to hold our counter
let x = 0;
// Init a varible to hold our setInterval timer, so we can disable it when conditions are met.
let counterInterval;
//Define our count() function
function count() {
if (x < 1000){
// Set the innerHTML (I'd rather innerText) to x + 1 as long as x is less than 1000
li1.innerHTML = x++;
} else {
// If x is equal to or greater than 1000, clear the timer
clearInterval(counterInterval);
}
}
//Start our interval time to run count() every 10ms and assign it to our counterInterval variable
counterInterval = setInterval(count,10)
<p id="li1"></p>

How can I make a set of numbers increase every second and for each increment, print the current set on a new line?

I have these set of 11 numbers that increase per second, but I want each increment or the current set of numbers to write on a new line. E.g;
20220215155
20220215156
20220215157 etc...
I tried adding the n tag buh it returned an error.
var i = 20220215155
function increment() {
i+, + </n>;
document.getElementById('test').innerHTML = i
}
('increment()', 1000);
Please I really need help as I have been trying to get this for so long.
Your code is not valid JS
Here is something that does work - I am using setInterval here
var i = 20220215155
function increment() {
i++; // increment
document.getElementById('test').innerHTML += i + "<br/>"; // add it with a breakline
}
setInterval(increment, 1000);
<div id="test"></div>
You can use a template literal for the string too
`${i}<br/>`
You can use setTimeout to call the function after a set time while also increasing the number you initially pass into the function.
// Cache the element
const test = document.querySelector('#test');
let n = 20220215155;
// `increment` accepts `n` as an argument
function increment(n) {
// Add a new HTML string to the element
test.innerHTML += `${n}</br>`;
// Call the function again with an new `n`
setTimeout(increment, 1000, ++n);
}
increment(n);
<div id="test"></div>
Additional documentation
Template/string literals

delay between function in loop jquery

I have a jQuery function that shows modal boxes:
function ShowAnonce(){
...
jQuery(".ShowAnonce").show();
jQuery(".ShowAnonce").animate({opacity: 1},300).delay(1800).animate({opacity: 0},300);
}
And what I want to do is to show this box 10 times with different random intervals. I used a for loop and setTimeout like this:
for(i=0;i<10;i++){
setTimeout(ShowAnonce(),Math.random()*100);
}
but it shows the box 10 times with no delay. What can I do to fix it?
Also, why can't I do the following at the end of ShowAnonce function?
jQuery(".ShowAnonce").hide();
If I do it, it doesn't shows me box because style display:none keeps being assigned.
Math.random() can return value in decimals also like , 0.123. Which the setTimeout() cannot take . Try Math.ceil (Math.random()) this will give you an integer but might give the same value again and again .
I would try (Math.ceil (Math.random()) *10 ).
As an alternative you can use setInterval as below instead of for loop for x number of times:
var x = 0;
var intervalID = setInterval(function () {
ShowAnnounce();
if (++x === 10) {
window.clearInterval(intervalID);
}
}, Math.random()*100);
Another post about each() iteration gave me an answer. So it works for me:
var time = 0;
for(i=0;i<10;i++){
time = time + Math.random() *10000;
setTimeout(ShowAnonce, time);
}

Changing global Variable from within function

Here im having a bit of an issue with this very simple script Ive written up. The aim for this script is to simply reduce the given number by one each time the button is clicked. I cannot appear to do this.. My global variable being the Number=100 doesnt appear to change, or change more than once.. Apologies for not being able to explain this well.
Here is the part im working on..:
<script>
var Number = 100; // Number i want changed and to keep changing each button click
function outcome() { // Button calls this function
Number = Number - 1; // Tries to change Global Number.. :/
}
document.write(Number); // Has the Number written in the document
</script>
Yes, conceptually this is right. Only you are not calling the function, at least not before writing Number to the document.
Btw, Number is the global reference to the Number constructor so you should use another variable name, lowercase at best.
var num = 100;
function outcome() {
num--;
}
outcome();
document.write(num); // 99
or
<script>
var num = 100;
function outcome() {
num--;
alert(num);
}
</script>
<button onclick="outcome()">Decrease!</button>
(Demo at jsfiddle.net)
You have to call your function:
<script>
var Number=100
function outcome(){
Number=Number-1
}
outcome(); // call the function here
document.write(Number)
</script>
or don't use a function in the first place:
<script>
var Number=100
Number=Number-1
document.write(Number)
</script>

JavaScript / jQuery or something to change text every some seconds

I need JavaScript or jQuery something to change text every few seconds... without the user doing anything.
Example:
"Welcome" changes to "Salmat datang" changes to "Namaste", etc. after 3 seconds and loops back.
As others have said, setInterval is your friend:
var text = ["Welcome", "Hi", "Sup dude"];
var counter = 0;
var elem = document.getElementById("changeText");
var inst = setInterval(change, 1000);
function change() {
elem.innerHTML = text[counter];
counter++;
if (counter >= text.length) {
counter = 0;
// clearInterval(inst); // uncomment this if you want to stop refreshing after one cycle
}
}
<div id="changeText"></div>
You may take a look at the setInterval method. For example:
window.setInterval(function() {
// this will execute on every 5 seconds
}, 5000);
You can use setInterval to call a function repeatedly. In the function you can change the required text.
The list of texts to change between could be stored in an array, and each time the function is called you can update a variable to contain the current index being used. The value can loop round to 0 when it reaches the end of the array.
See this fiddle for an example.
setInterval(function(){
alert('hello, do you have a beer?');
}, 1000);
where 1000 ms = 1 second.

Categories

Resources