JQuery count up with a timeout or endpoint - javascript

I have a timer which counts up to a figure based on a set of results from the database. however, when the data isnt present the timer will just keep going with no timeout or end point.
Is there a way I can either not show the timer if the value does not exist or show 0/40 see my code below:
$(function() {
function count($this) {
var current = parseInt($this.html(), 10);
$this.html(++current);
if (current !== $this.data('count')) {
setTimeout(function(){
count($this)
}, 50);
}
}
$(".fiveStarScore").each(function() {
$(this).data('count', parseInt($(this).html(), 10));
$(this).html('0');
count($(this));
});
});
This is the div that is targeted and will stop at the desired value.
<div>
<span class="fiveStarScore"><?php echo $total_five_stars;?></span>/40
</div>

You can fix this by checking if the text value of the element on load is 0 (or is any non numerical value) and not calling count() if so:
$(function() {
function count($el) {
var current = parseInt($el.text(), 10);
$el.html(++current);
if (current !== $el.data('count')) {
setTimeout(function() {
count($el)
}, 50);
}
}
$(".fiveStarScore").each(function() {
var $el = $(this);
var total = parseInt($el.text(), 10) || 0;
$el.data('count', total).text('0');
if (total == 0)
return;
count($el);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span class="fiveStarScore">0</span>/40
</div>
<div>
<span class="fiveStarScore">25</span>/40
</div>

Related

Index not being counted on click

I have a slider where I want to keep track of the current position of the slider. The function that runs when the ('next') and ('prev') are being clicked, is supposed to log the current position of the slider.
Unfortunately it skips the first child and starts the count on the second item in the slider. Instead of the first item being index 0, the second item is index 0
$(document).foundation()
$('.bullet').first().addClass('active');
//sets first item to active
$('.slider-item').first().addClass('active');
function dec() {
var $this = $(this);
var current = $('.slider-items').find('.active');
var position = $('.slider-items').children().index(current);
console.log(position)
}
$('.next, .prev').click(function() {
dec();
var $this = $(this);
var current = $('.slider-items').find('.active');
var position = $('.slider-items').children().index(current);
var numItems = $('.slider-item').length;
if ($this.hasClass('next')) {
if (position < numItems - 1) {
$('.active').removeClass('active').next().addClass('active');
} else {
$('.slider-item').removeClass('active').first().addClass('active');
$('.bullet').removeClass('active').first().addClass('active');
} //else
} else {
if (position === 0) {
$('.slider-item').removeClass('active').last().addClass('active');
$('.bullet').removeClass('active').last().addClass('active');
} else {
$('.active').removeClass('active').prev().addClass('active');
}
}
}); // click function
The code seems to work when I run it against a simple bullet list example. It correctly states that the first bullet point is index 0. Are you simply calling the dec() function in the wrong place? Note that when you click next, you are logging the current position before the change is made to the position. I updated the dec() code to accept a parameter to show what I mean.
$(document).ready(function() {
//sets first item to active
$('.slider-item').first().addClass('active');
function dec(prefix) {
var $this = $(this);
var current = $('.slider-items').find('.active');
var position = $('.slider-items').children().index(current);
console.log(prefix + position);
}
$('.next, .prev').click(function() {
dec("before click handled: ");
var $this = $(this);
var current = $('.slider-items').find('.active');
var position = $('.slider-items').children().index(current);
var numItems = $('.slider-item').length;
if ($this.hasClass('next')) {
if (position < numItems - 1) {
$('.active').removeClass('active').next().addClass('active');
} else {
$('.slider-item').removeClass('active').first().addClass('active');
$('.bullet').removeClass('active').first().addClass('active');
} //else
} else {
if (position === 0) {
$('.slider-item').removeClass('active').last().addClass('active');
$('.bullet').removeClass('active').last().addClass('active');
} else {
$('.active').removeClass('active').prev().addClass('active');
}
}
dec("after click handled: ");
})}); // click function
li.active {
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="slider-items">
<li class="slider-item">A</li>
<li class="slider-item">B</li>
<li class="slider-item">C</li>
<li class="slider-item">D</li>
</ul>
<button class="prev">Prev</button>
<button class="next">Next</button>

jQuery. How do I select live created element?

Here is the code:
helpers.ajaxModuleFormRequest('blockcallback', $(this), function() {
var timer = $('[data-timer]');
var seconds = timer.data('timer');
var interval = setInterval(function() {
if (seconds == 0) {
clearInterval(interval);
}
timer.text(seconds);
seconds--;
}, 1000);
});
helper.ajaxModuleFormRequest() does an AJAX-request and then in $.ajax.done() method calls callback-function specified in 3rd param.
<div data-timer="20"></div> is inserted in DOM live $.ajax.done() method and I want to select it to start the timer. But the code doesn't work, $('[data-timer]').length returns 0. How can I fix this?
Here's a simplified example, which inserts a <div> dynamically and then starts the timer:
Html:
<html>
<head>Testpage</head>
<body></body>
</html>
JavaScript:
{
$('body').append('<div data-timer="20"></div>');
var timer = $('[data-timer]');
var seconds = timer.data('timer');
if (seconds!==undefined)
{
alert(seconds);
var interval = setInterval(function() {
if (seconds == 0) {
alert('elapsed!');
clearInterval(interval);
}
timer.text(seconds);
seconds--;
}, 1000);
}
else
{
alert("Please specify a timer value!");
}
}
Note that initially the <div> is not there, it is inserted dynamically via
$('body').append('<div data-timer="20"></div>');
If you want to test whether it tests correctly for existance of the timer value, comment the line above, i.e.
// $('body').append('<div data-timer="20"></div>');
and you'll get the alert message "Please specify a timer value!".
Try it on jsfiddle:
jsfiddle
{
$('body').append('<div data-timer="20"></div>');
var timer = $('[data-timer]');
var seconds = timer.data('timer');
if (seconds!==undefined)
{
alert(seconds);
var interval = setInterval(function() {
if (seconds == 0) {
alert('elapsed!');
clearInterval(interval);
}
timer.text(seconds);
seconds--;
}, 1000);
}
else
{
alert("Please specify a timer value!");
}
}
<head>Testpage</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How do I display a div when my timer hits zero?

here's my code:
$('#TESTER').hide();
$('#titlehead2').click(
function() {
var doUpdate = function() {
$('.countdown').each(function() {
var count = parseInt($(this).html());
if (count !== 0) {
$(this).html(count - 1);
}
});
};
setInterval(doUpdate,1000);
if(count <= 0) $('#TESTER').show();
}
);
#TESTER is the div I want to display when the timer reaches zero, and #titlehead2 is my play button for the timer. Any help will be much appreciated.
You need to check the value of counter within the timer
$('#TESTER').hide();
$('#titlehead2').click(function () {
var doUpdate = function () {
//need to look whether the looping is needed, if there are more than 1 countdown element then the timer logic need to be revisted
$('.countdown').each(function () {
var count = parseInt($(this).html());
if (count !== 0) {
$(this).html(count - 1);
} else {
$('#TESTER').show();
//you also may want to stop the timer once it reaches 0
clearInterval(timer);
}
});
};
var timer = setInterval(doUpdate, 1000);
});

Display diffrent image depending on timer

I'm trying to display a different image depending on the timer's result and can't find a way through. So far I have a start and stop button, but when I click stop, I want to use the value the timer is on and display an image(on alertbox or the webpage itself) depending on that value.
if( timer =>60){
img.src("pizzaburnt.jpg");
}elseif (timer <=30){
img.src("pizzaraw.jpg");
}
else{
img.src("pizzaperfect.jpg
}
///Time
var check = null;
function printDuration() {
if (check == null) {
var cnt = 0;
check = setInterval(function () {
cnt += 1;
document.getElementById("para").innerHTML = cnt;
}, 1000);
}
}
//Time stop
function stop() {
clearInterval(check);
check = null;
document.getElementById("para").innerHTML = '0';
}
**HTML**
<td>
Timer :<p id="para">0</p>
</td>
Any advice or dicussion would be great, thanks.
Something like this would work better and it's more compact:
var img = document.getElementById("image");
var imageSrcs = ['pizzaRaw.jpg', 'pizzaPerfect.jpg', 'pizzaBurnt.jpg'];
var imageIndex = 0;
var interval = setInterval(animate, 30000); //change image every 30s
var animate = function() {
//change image here
//using jQuery:
img.src(imageSrcs[imageIndex]);
imageIndex++; //move index for next image
if (imageIndex == imageSrcs.length) {
clearInterval(interval); //stop the animation, the pizza is burnt
}
}
animate();
Reason you wouldn't want to use an increment variable and a 1 second timer is because your just conflating your logic, spinning a timer, and making a bit of a mess when all you really want is the image to change every 30 seconds or whenever.
Hope this helps.
You need an <img> tag in your HTML like this:
<html>
<body>
Timer: <p id="para">0</p>
Image: <img id="image" />
</body>
</html>
And the Javascript code will be like:
var handle;
var timerValue = 0;
var img = document.getElementById( "image" );
var para = document.getElementById("para");
function onTimer() {
timerValue++;
para.innerHTML = timerValue;
if ( timerValue >= 60 ) {
img.src( "pizzaburnt.jpg" );
}else if ( timer <= 30 ) {
img.src( "pizzaraw.jpg" );
} else {
img.src("pizzaperfect.jpg" );
}
}
function start () {
if ( handle ) {
stop();
}
timerValue = 0;
setInterval( onTimer, 1000 );
}
function stop () {
if ( handle ) {
clearInterval ( handle );
}
}
Please make sure that these 3 files are in the same directory as your HTML file:
pizzaburnt.jpg
pizzaraw.jpg
pizzaperfect.jpg

How to stop my javascript countdown?

How can I stop my javascript function when countdown = 0?
JS:
var settimmer = 0;
$(function(){
window.setInterval(function() {
var timeCounter = $("b[id=show-time]").html();
var updateTime = eval(timeCounter)- eval(1);
$("b[id=show-time]").html(updateTime);
}, 1000);
});
HTML:
<b id="show-time">20</b>
For one thing remove those evals. They don't do anything.
Then all you have to do is clear the timer when it reaches zero.
$(function(){
var timer = setInterval(function() {
var timeCounter = parseInt($("b[id=show-time]").text());
$("b[id=show-time]").text(--timeCounter); // remove one
if(!timeCounter) clearInterval(timer);
}, 1000);
});
It is easy! When you call setInterval it return an ID, so you can destroy the interval later. To destroy it you must use clearInterval(id), and voilà!
It works like this:
// Activate timer
var iv = window.setInterval(...);
// Deactive timer
window.clearInterval(iv);
Also you should use parseInt() instead of eval():
$(function() {
// Read the start value once and store it in a variable
var timeCounter = parseInt( $("b[id=show-time]").text() );
// Active the counter
var iv = window.setInterval(function() {
// Decrement by one and write back into the document
$("b[id=show-time]").text(--timeCounter);
// Check if counter == 0 -> stop counting
if (0 == timeCounter) {
window.clearInterval(iv);
// ...do whatever else needs to be done when counter == 0 ..
}
}, 1000);
});
Example:
var i = 0,
pid = setInterval(function() {
if (++i > 10)
clearInterval(pid);
}, 1000);
Based on what you wanted for your code ...
$(function() {
var el = document.getElementById('show-time'),
pid = setInterval(function() {
// (s - i) coerces s to Number
var t = el.innerHTML - 1;
el.innerHTML = t;
if (t < 1)
clearInterval(pid);
}, 1000);
});
Keep in mind that JS won't be 100% accurate with its timing.
Pasted code below or see the fiddle: http://jsfiddle.net/raHrm/
<script type="text/javascript">
$(function(){
var settimmer = 0,
timeCounter = $("#show-time").html(),
updateTime = timeCounter;
(function countDown() {
timeCounter = $("#show-time").html();
updateTime = parseInt(timeCounter)-1;
$("#show-time").html(updateTime);
if ( updateTime ) {
setTimeout(countDown, 1000);
}
})();
});​
</script>
Set the timer to a variable, then use clearInterval in-order to stop the loop. As for catching the end, use a simple conditional:
$(function(){
var elem=$('strong[id="show-time"]'),settimmer=0,updateTime,t;
t=window.setInterval(function() {
updateTime=parseFloat(elem.html(),10)-1;
if(updateTime==0) {
window.clearInterval(t);
elem.html('Done!');
} else {
elem.html(updateTime);
}
},1000);
});
Then in the HTML:
<strong id="show-time">20</strong>
The <b> tag is depreciated, try to avoid using it. Also, there is no reason to eval() the HTML you are getting from the element; a simple parseFloat() works just fine.

Categories