I am trying to making live variable which updates every second which works but when I add count function there then there I can see 0 for 1 second and after that variable shows without animation. My goal is to make variable which at first load page counts from 0 to "var. value" for example 18 and if variable change for example to 20, then there will be count ani. from 18 to 20. I don't actually know how I can achieve it because I can't get previous variable because it's store in global_users.php
index.php
<script>
$(document).ready(function() {
$("#players").load("global_users.php")
setInterval(function () {
$("#players").load("global_users.php")
}, 1000);
});
</script>
<span class="Count" id="players"></span>
<script>
$('.Count').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 1000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
</script>
global_users.php
<?php
include("php/server.php");
echo $total_online = $serverInfo['Players'];
?>
The issue lies in the usage of .load() method, which can be useful, but not for this case. Under the hood of .load() is $.ajax() which allows you to make a request to the server with jQuery. Use it to get access to the player count value that the server returns with each request.
Split up the code in two functions, one for getting the player count and one for updating the player count with an animation. Whenever the first function has downloaded a new count and that count is different from the one that you already have, call the second function to update and animate.
<span class="count" id="players"></span>
$(document).ready(function() {
// Set starting count.
let count = 0;
const $players = $('#players');
/**
* Updates the player count with an animation and
* saves the new player count.
*/
function updatePlayerCount(newCount) {
$({
counter: count // Starting value, which is the last known count value.
}).animate({
counter: newCount // Value to animate to, which is the new count value.
}, {
duration: 1000,
easing: 'swing',
step: function() {
$players.text(Math.ceil(this.counter));
},
complete: function() {
count = newCount; // Update the count value after the animation to compare it later again.
}
});
}
/**
* Gets the count value from the server and
* passes it to the updatePlayerCount function
* if the count has been changed.
*/
function getPlayerCount() {
$.ajax({
url: 'global_users.php',
method: 'GET'
}).done(function(newCount) {
newCount = Number(newCount); // Makes sure that the value is a number.
if (count !== newCount) {
updatePlayerCount(newCount); // newCount is a different value than count, so updatePlayerCount is called.
}
});
}
// Execute getPlayerCount every 5 seconds.
setInterval(getPlayerCount, 5000);
});
Related
I would like to know how can I change the background-image of another div element, when I click on it. I would like to see images one after another in order but what I get is the last one. Here is some code:
$(document).ready(function () {
// console.log('ready!');
$('.right').click(function () {
$('.zur-gda-img').css('background','url(images/sail-boat.jpg)');
}).click(function() {
$('.zur-gda-img').css('background','url(images/sad_ostateczny.jpg)');
}) }).click(function() {
$('.zur-gda-img').css('background','url(images/twierdza_wisloujscie.jpg)');
});
Instead of adding multiple event handler use single. Inside handler change images from the array with help of a counter variable.
$(document).ready(function() {
// store images in an array
var images = ['url(images/sail-boat.jpg)', 'url(images/sad_ostateczny.jpg)', 'url(images/twierdza_wisloujscie.jpg)'],
// variable to store index
i = 0;
$('.right').click(function() {
// update index based on array length
i = i % images.length;
// update background from array using the index value
$('.zur-gda-img').css('background', images[i++]);
})
});
You don't need three event handlers for this (they will just fire one after another and you'll only see the last image). If you want to see images changing, try the following:
$(document).ready(function () {
// document has loaded
$('.right').click(function () {
// 1st image:
$('.zur-gda-img').css('background','url(images/sail-boat.jpg)');
// 2nd image, appears in a second:
setTimeout(function() {
$('.zur-gda-img').css('background','url(images/sad_ostateczny.jpg)');
// 3rd image, appears in another second:
setTimeout(function() {
$('.zur-gda-img').css('background','url(images/twierdza_wisloujscie.jpg)');
},
1000);
},
1000);
});
});
I the given code, I am using setInterval() and clearInterval() methods.
Here are two buttons for setInterval() and two for clearInterval(), if I click both setInterval() buttons, then the clearInterval() buttons doesn't work.
HTML:
<div id="a"></div>
<button id='bt1'>start</button>
<button id='bt2'>Stop</button>
<button id='bt3'>Start</button>
<button id='bt4'>Stop</button>
Javascript:
var Graph = {
graph: null,
start: function (i) {
this.graph = setInterval(function () {
$('#a').html(i++);
}, 1000);
},
stop: function () {
window.clearInterval(this.graph);
}
};
$('#bt1').click(function(){
Graph.start(1);
});
$('#bt2').click(function(){
Graph.stop();
});
$('#bt3').click(function(){
Graph.start(1);
});
$('#bt4').click(function(){
Graph.stop();
});
Fiddle: Fiddle
As the other answers, the first timer ID is overwritten. Try to store the IDs separately in an array or at least as separate variable names. Here is one adjustment using an array:
var Graph = {
graph: [0, 0], /// turn this into an array
start: function(id, i) { /// add a new parameter here
this.graph[id] = setInterval(function () {
$('#a').html(i++);
}, 1000);
},
stop: function (id) { /// add parameter here as well
window.clearInterval(this.graph[id]);
}
};
$('#bt1').click(function(){
Graph.start(0, 1); /// set index 0 with this timer id
});
$('#bt2').click(function(){
Graph.stop(0); /// stop using id at index 0
});
$('#bt3').click(function(){
Graph.start(1, 1); /// etc.
});
$('#bt4').click(function(){
Graph.stop(1);
});
Your i variable may be subject to the same thing depending on what you try; I haven't addressed that here.
Hope this helps.
You only have a single variable to store the result of both calls to setInterval, i.e. you are overwriting it on the second call so the first timer can't be cleared.
The clearInterval() method clears a timer set with the setInterval() method.
The ID value returned by setInterval() is used as the parameter for the clearInterval() method.
Note: To be able to use the clearInterval() method, you must use a global variable when creating the interval method:
myVar = setInterval("javascript function",milliseconds);
Then you will be able to stop the execution by calling the clearInterval() method.
You can also refer to this answer
If you click the #bt1 button and then the #bt3 button, the second start() function call will overwrite the graph variable in the Graph object. So the ID value returned by first setInterval() call is lost, you cannot clear the first timer.
Just put the following line of code before the setInterval() call in the start() method. This will stop the previous running timer:
if (this.graph) { this.stop(); }
Like this:
var Graph = {
graph: null,
start: function (i) {
if (this.graph) { this.stop(); }
this.graph = setInterval(function () {
$('#a').html(i++);
}, 1000);
},
stop: function () {
window.clearInterval(this.graph);
}
};
$('#bt1').click(function(){
Graph.start(1);
});
$('#bt2').click(function(){
Graph.stop();
});
$('#bt3').click(function(){
Graph.start(1);
});
$('#bt4').click(function(){
Graph.stop();
});
I would like to perform a different action every 60 seconds to change my background via animate.
Now run by clicking.
$(document).ready(function(){
$("li.one").click( function(){
$('#switch-container').animate({backgroundColor: '#18597f'}, 1000)
});
$("li.two").click( function(){
$('#switch-container').animate({backgroundColor: '#8a0651'}, 1000)
});
$("li.three").click( function(){
$('#switch-container').animate({backgroundColor: '#8a0651'}, 1000)
});
how could I do this? Thanks!
var colors = ['#18597f','#8a0651','#8a0651'],
timer = setInterval(function() {
var rand = parseInt(Math.random()*(3 - 0),10);
$('#switch-container').animate({backgroundColor: colors[rand]}, 1000);
}, 1000);
FIDDLE
EDIT:
to change colors in a regular order and not randomly:
var colors = ['green','red','yellow'],
i = 0,
timer = setInterval(function() {
$('#switch-container').animate({backgroundColor: colors[i++]}, 500);
i = i==3 ? 0 : i;
}, 1000);
FIDDLE
Use setInterval().
The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).
setInterval(function(){
//code for animation
},DURATION);
$(document).ready(function () {
// alert("hello");
changecolor();
});
function changecolor() {
// alert("hi");
var colors = ["#00FF00", "#CCCCCC", "#990099", "#FEA400", "#FF9900", "#6600FF", "#333333", ];
var rand = Math.floor(Math.random() * colors.length);
$('#controls-wrapper').css("background-color", colors[rand]);
setTimeout('changecolor()', 100);
}
If you don't care if the code within the timer may take longer than your interval, use setInterval():
setInterval(function, delay)
That fires the function passed in as first parameter over and over.
A better approach is, to use setTimeout along with a self-executing anonymous function:
(function(){
// do some stuff
setTimeout(arguments.callee, 60000);
})();
that guarantees, that the next call is not made before your code was executed. I used arguments.callee in this example as function reference. It's a better way to give the function a name and call that within setTimeout because arguments.callee is deprecated in ecmascript 5.
I used this template once: http://luiszuno.com/themes/kroft/
It has an animated background. Check the html files for the html, the slider.js file for your variable time and the slides folder for the backend jquery code
I have this function in jQuery that gets data from a page with POST, then sets the response into a div:
$("#go").click(function(){
$.post("get.php", {p: 'abc'}, function(data){
$('#result').html(data);
});
});
This works, but is there anyway to delay the data going into the #result tag by about 3 seconds?
Eventually I want the tag to say:
"Loading.", "Loading..", and "Loading..." for a second each, then show the data.
This is the syntax you should use.
var delayCounter = 3;
var delayTimer = '';
delayTimer = setInterval(function(){
if (delayCounter > 0){
$('#result').html('Loading...');
}else{
$('#result').html(data);
clearInterval(delayTimer);
}
delayCounter--;
},1000);
Whats happening here?
We use the delayCounter variable to count how many times we have delayed the action. Its starting value is 3 - so we will be "delayed" 3 times.
The delayTimer variable is the timer itself that will count each delay.
We use the setInterval function becuase that is exactly what we are wanting to do - set intervals between executing our code.
The clearInterval is pretty self explanatory - this ends and clears the timer.
For each iteration we decrease the delayCounter variable so that we can keep track of how many intervals have passed.
We use miliseconds to define the delay - here I have used 1000 which is 1 seconds (1000 milliseconds in one second).
One more addition you might like to implement is that instead of simply placing the "Loading" text in your element, to make it a little bit more dynamic by appending text to it.
What might be fun is to append the ellipsis to the word "Loading" to get an effect like :
First set the initial value to "Loading" then append each dot -
$('#result').html($('#result').html()+'.');
// Loading
// Loading.
// Loading..
// Loading...
That said you could also just take the animated gif and use that lazy-programmers :P
Try:
setTimeout(function() {
$('#result').html(data);
}, 3000);
To delay the execution of a function in JavaScript use the setTimeout method. Works a little like:
var doLater = setTimeout(function(){
alert('I like to wait 5 seconds');
},5000); //delay is stated in ms
In your case that would end up in:
$("#go").click(function(){
$.post("get.php", {p: 'abc'}, function(data){
var wait = setTimeout(function(){$('#result').html(data);},3000);
});
});
Edit: updated to add loading functionality.
$("#go").click(function(){
$.post("get.php", {p: 'abc'}, function(data){
window.intervalTimer = setInterval(function(data) {
if (!window.timeoutCount)
window.timeoutCount = 0;
if (++window.timeoutCount > 3) {
$('#result').html(data);
clearInterval(window.intervalTimer);
}
else
$('#result').html("Loading..")
}, 1000);
});
});
Try this:
$("#go").click(function(){
// Show loader here
$.post("get.php", {p: 'abc'}, function(data){
setTimeout(function () {
// Hide loader here
$('#result').html(data);
}, 3000);
});
});
$("#go").click(function(){
$.post("get.php", {p: 'abc'}, function(data) {
$('go').html('Loading.');
setTimeout("function() {
$('go').html('Loading..');
}",1000);
setTimeout("function() {
$('go').html('Loading...');
}",1000);
$('#result').html(data);
}
}
I am using a plugin called anything slider and am trying to make the controls fade after 4 seconds (which is working) then change opacity back to 1 on mouseover (not working). Here is what I have so far...what am I doing wrong?
$(slider.$controls).mouseover(function()
slider.$controls.fadeTo(400, 1.0);
});
$(function () {
var fadeTime = 400,
fadeDelay = 4000,
timer, hideControls = function (slider) {
clearTimeout(timer);
setTimeout(function () {
slider.$controls.fadeTo(fadeTime, 0.3);
$('.tooltip').fadeOut(fadeTime);
}, fadeDelay);
};
});
you sould replace every slider.$controls.fadeTo with slider.controls.fadeTo
$(slider.controls).mouseover(function()
$(this).fadeTo(400, 1.0);
});
You have a syntax error on line 2. Where you have
slider.$controls.fadeTo...
you should have
$(this).fadeTo...
because once you've entered the anonymous function on line 1, the this object now refers to the DOM element upon which you're executing this code, which is the element represented by slider.controls.
First you use slider.controls to target the control element(s), then you use slider.$controls to target the same element(s). I think you need to decide which one it is.
Also, inside a callback function you can use this as a reference to the element that has had the event fired on it:
$(slider.controls).bind('mouseover', function () {
$(this)...
});
Otherwise if you want to fade-in-out all the controls at the same time then you just need to figure out if you need to use slider.$controls or slider.controls.
UPDATE
I see you have changed your question and now you are using slider.$controls both times. You should put your mouseover code inside the document.ready event handler so you know the DOM elements are available:
$(function () {
slider.$controls.mouseover(function()
slider.$controls.fadeTo(400, 1.0);
});
var fadeTime = 400,
fadeDelay = 4000,
timer, hideControls = function (slider) {
clearTimeout(timer);
setTimeout(function () {
slider.$controls.fadeTo(fadeTime, 0.3);
$('.tooltip').fadeOut(fadeTime);
}, fadeDelay);
};
Also I noticed that you wrapped slider.$controls in a jQuery object the first time, but not the second, make sure to do that if slider.$controls is not already a jQuery object (many times developers put a $ as the first character of a variable name to denote that it is a jQuery object).