Call a function outside of a dynamic jquery slider - php

I am dynamically creating my sliders and in the "Slide" event and "Stop" event I would like to call a function that is defined in the non dynamic content. I can get the functions to work if I create them each time with the slider, but that seems like a lot of redundant code?
Non Dynamic function
$(document).ready(function() {
var converSecondsToMinutes;
convertSecondsToMinutes = function(secondsEntered){
var secondsEntered = secondsEntered;
var time = parseInt(secondsEntered,10);
time = time < 0 ? 0 : time;
var minutes = Math.floor(time / 60);
var seconds = time % 60;
minutes = minutes < 9 ? "0"+minutes : minutes;
seconds = seconds < 9 ? "0"+seconds : seconds;
var newTime = minutes+":"+seconds
console.log(newTime);
return newTime
}
});
Dynamic jQuery slider
<?php
query...
result...
for(...){
?>
<Script>
$( "#slider"+<?php echo $id; ?> ).slider({
animate: true ,
value: 0,
min: 0,
//dynamic grab this
max: <?php echo $playtime_seconds; ?>,
step: 0.01,
start: function( event, ui ) {
....
},
slide: function( event, ui ) {
audio = ....
audio.currentTime = ui.value;
progress_seconds = parseFloat(audio.currentTime.toFixed(2));
progress_seconds = $(function(){convertSecondsToMinutes(progress_seconds);});
$('#progress_seconds'+<?php echo $id; ?>).html(progress_seconds);
},
stop: function( event, ui ) {
....
}
}
});
});
}
I cut and paste the parts of the code that were important to the question.
This is the line that is not working: $('#progress_seconds'+).html(progress_seconds);

You edited just after I commented, so my comment no longer made sense, the $(function(){ part of your code is not necessary, try just using:
progress_seconds = converSecondsToMinutes(progress_seconds);
And spelling errors in code are a real issue with me, conver has a t at the end.
There is also no need to wrap your function in $(document).ready(), declare it like this:
function convertSecondsToMinutes(secondsEntered)
{
var time = ...
...
}

Related

Run jQuery Counter with value from MySQL

I have jQuery counter which move numbers from one fixed number to other fixed number. But I want to create the Counter which end at number which come from MySQL database.
Counter Function Code:
Now It starts value from 99950 and end value is 100000 but I want to change end value. It should be the value which I fetch from mysql.
<script type="text/javascript">
(function($) {
$.fn.countTo = function(options) {
// merge the default plugin settings with the custom options
options = $.extend({}, $.fn.countTo.defaults, options || {});
// how many times to update the value, and how much to increment the value on each update
var loops = Math.ceil(options.speed / options.refreshInterval),
increment = (options.to - options.from) / loops;
return $(this).each(function() {
var _this = this,
loopCount = 0,
value = options.from,
interval = setInterval(updateTimer, options.refreshInterval);
function updateTimer() {
value += increment;
loopCount++;
$(_this).html(value.toFixed(options.decimals));
if (typeof(options.onUpdate) == 'function') {
options.onUpdate.call(_this, value);
}
if (loopCount >= loops) {
clearInterval(interval);
value = options.to;
if (typeof(options.onComplete) == 'function') {
options.onComplete.call(_this, value);
}
}
}
});
};
$.fn.countTo.defaults = {
from: 0, // the number the element should start at
to: 100, // the number the element should end at
speed: 1000, // how long it should take to count between the target numbers
refreshInterval: 100, // how often the element should be updated
decimals: 0, // the number of decimal places to show
onUpdate: null, // callback method for every time the element is updated,
onComplete: null, // callback method for when the element finishes updating
};
})(jQuery);
jQuery(function($) {
$('.timer').countTo({
from: 99950,
to: 100000,
speed: 2000,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
});
</script>
HTML Code:
<h2><span class="timer" style="color:#F44336;font-weight:700; font-size:20px;"></span></h2>
You will need a server side language for getting data extracted from mysql. Say for instance, if you are using PHP as your server side language, in that case you can simply put :
<?php
mysql_connect('host','username','password') or die();
mysql_select_db('your_database_name') or die();
$query='SELECT `min_count`, `max_count` FROM 'your_table_name`;
$row=mysql_query($query);
while($rs=mysql_fetch_array($row)){
$from=$rs[0];
$to=$rs[1];
}
?>
<script type="text/javascript">
(function($) {
$.fn.countTo = function(options) {
// merge the default plugin settings with the custom options
options = $.extend({}, $.fn.countTo.defaults, options || {});
// how many times to update the value, and how much to increment the value on each update
var loops = Math.ceil(options.speed / options.refreshInterval),
increment = (options.to - options.from) / loops;
return $(this).each(function() {
var _this = this,
loopCount = 0,
value = options.from,
interval = setInterval(updateTimer, options.refreshInterval);
function updateTimer() {
value += increment;
loopCount++;
$(_this).html(value.toFixed(options.decimals));
if (typeof(options.onUpdate) == 'function') {
options.onUpdate.call(_this, value);
}
if (loopCount >= loops) {
clearInterval(interval);
value = options.to;
if (typeof(options.onComplete) == 'function') {
options.onComplete.call(_this, value);
}
}
}
});
};
$.fn.countTo.defaults = {
from: 0, // the number the element should start at
to: 100, // the number the element should end at
speed: 1000, // how long it should take to count between the target numbers
refreshInterval: 100, // how often the element should be updated
decimals: 0, // the number of decimal places to show
onUpdate: null, // callback method for every time the element is updated,
onComplete: null, // callback method for when the element finishes updating
};
})(jQuery);
jQuery(function($) {
$('.timer').countTo({
from: <?php echo "$from"; ?>,
to: <?php echo "$to"; ?>,
speed: 2000,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
});
Do you mean, you want to get an sql query to the counter?
You could use AJAX for that, make a php file with an sql query and call it from the script using Ajax.
jQuery code:
$.ajax({
type: "POST",
dataType: "json",
url: 'endpoint to php script',
success: function(data) {
$('.timer').countTo({
from: data.startFrom,
to: data.endOn,
speed: 2000,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
},
error: function(error) {
console.log(error);
}
});
PHP code:
<?php
//I assume you know how connect to your database and get data
header("Content-Type: application/json", true);
$result = array(
'startFrom' => 1000,
'endOn' => 9000
);
echo json_encode($result);
I thnik it's clear and explain this code is not needed

call a function with different parameters in setInterval

I am using setInterval function to call a function after a particular time intervals.
Code is given below:
var refreshIdd = setInterval(function() {
loadData(page);
}, <?= $h; ?>);
For example: If the time interval ie $h is 1000(1 sec) I have to call the function loadData with parameter 1. In the second second i have to call loadData 2.In Each time interval I have to pass 1,2,3 etc.If the $h is 2000 ie 2sec,I have to call loadData after 2nd second with parameter 1 and with parameter 2 in 4th second and so on
How can I do this?
This is independent of $h.
Set page = 1 and do a simple increment with page++. This would increase the value of page by 1 every time it is called.
var page = 1;
var refreshIdd = setInterval(function() {
loadData(page++);
}, <?=$h?>);
See simple demo.
You can create a separate function to get diff params.
var paramValue = 0;
var refreshIdd = setInterval(function() {
param = getParam();
loadData(param);
}, <?= $h; ?>);
function getParam() {
return ++paramValue;
}
(OR)
Simple as,
var paramValue = 0;
var refreshIdd = setInterval(function() {
loadData(++paramValue);
}, <?= $h; ?>);

JavaScript Countdown (counting up) milliseconds too quick, wont load next page?

javascript too fast when i set setInterval(function() down (or up i guess, speed wise) to 100 or 500 and wont load mypage.php as it doesn't have time i think? don't want to slow counter down either. so is there a php equivalent that can? (with the little number display like this, see jsfiddle) or is there a better javascript counter ? would prefer php, any ideas?
Thanks heaps, any help would be great.
Changed the page link to # as it will freeze things otherwise
http://jsfiddle.net/aEXgB/2/ Also added exit;but didn't help.
<html>
<head>
<script type="text/javascript">
function countdown() {
var i = document.getElementById('counter');
if (parseInt(i.innerHTML)>=3000) {
location.href = 'mypage.php';
exit;
}
i.innerHTML = parseInt(i.innerHTML)+1;
}
setInterval(function(){ countdown(); },.75);
</script>
</head>
<body>
<div style="margin-left:20px; float:left;"><p>Countdown:<font color="#33CC00"> <span id="counter">10 </span></font></p></div>
</body>
</html>
replace
setInterval(function(){ countdown(); },.75);
with
var t = setInterval(function(){ countdown(); },.75);
then just before the exit in the function, add;
clearInterval(t);
First, I don't understand why it's called a countdown when you count UP.
Second, I think it's better to update the counter and THEN check the value. That way you don't have an extra call to the coundown function.
Third, clear the interval before changing location because the interval is probably getting fired again too quickly.
Fourth, this won't actually work in jsfiddle because of how jsfiddle uses iframes :)
var interval = setInterval(function(){ countdown(); },.75);
function countdown() {
var i = document.getElementById('counter');
i.innerHTML = parseInt(i.innerHTML)+1;
if (parseInt(i.innerHTML)>=3000) {
clearInterval(interval);
window.location.href = "mypage.php";
}
}
JS:
var sec = 0;
var interval = 750; // milliseconds
var stop = 5; // seconds
function pad ( val ) { return val > 9 ? val : "0" + val; }
setInterval( function(){
if(document.getElementById("seconds").innerHTML < stop) {
document.getElementById("seconds").innerHTML=pad(++sec%60);
} else {
location.href = 'http://google.nl'
}
}, interval);
Html:
<div id="seconds></div>
Fiddle:
http://jsfiddle.net/5tM3A/5/

javascript timer not counting down when retrieving time from db

I am trying to follow a jsfiddle example to create a time in javascript:
http://jsfiddle.net/g3rRJ/
Now obviously the timer in the jsfiddle works fine. But the issue I have is that the time which the timer starts from comes for a mysqli/php variable where it retrieves the time from the db.
So except for:
<span id="countdown">01:30:10</span>
I have to have it as:
echo "<p><span id='countdown'>" . $dbSessionDuration . "</span></p>";
AND
except for:
var time = "01:30:10",
I have to have it as:
var time = <?php echo json_encode($dbSessionDuration); ?>,
Now I am getting no errors but what is happening is that the timer is not doing a count down. My question is why is it not counting down? An example of the time from the variable could be 01:00:00.
Below is the code for the function:
echo "<p><span id='countdown'>" . $dbSessionDuration . "</span></p>";
...
<script type="text/javascript">
(function(){
$(document).ready(function() {
var time = <?php echo json_encode($dbSessionDuration); ?>,
parts = time.split(':'),
hours = +parts[0],
minutes = +parts[1],
seconds = +parts[2],
span = $('#countdown');
function correctNum(num) {
return (num<10)? ("0"+num):num;
}
var timer = setInterval(function(){
seconds--;
if(seconds == -1) {
seconds = 59;
minutes--;
if(minutes == -1) {
minutes = 59;
hours--;
if(hours==-1) {
alert("timer finished");
clearInterval(timer);
return;
}
}
}
span.text(correctNum(hours) + ":" + correctNum(minutes) + ":" + correctNum(seconds));
}, 1000);
});
});
</script>
Change this:
});
});
</script>
to this:
});
})(); // ← note the extra parentheses
</script>
so that you actually call your anonymous function. (Alternatively, you can simply remove its (function(){ and }); entirely. There's no reason for this code to be in a function at all.)
I don't know if this was a mistype but I was able to run this code by adding $, $(function(){, at the first part of your anonymous function. I'm assuming your value from the db comes in as hours:mins:secs. I'm not sure why Fiddler ran but I had to add that to get it to work in my environment.

jQuery - Animate & Time interval

<script>
$(document).ready(function() {
$.get("database.php", function(data){
var xp = data + "%";
$('#exp_bg').animate({
width: xp
}, 1500, function() { });
});
});
</script>
Database.php:
<?php
$xp = 50;
$level = 100;
$xp_percent = $xp * 100 / $level;
echo $xp_percent;
?>
What i'm trying to do, is that if $xp_percent increases in database.php, then #exp_bg's width will animate into desired width without refresh.
I tried to do that with time interval, which takes data from database.php every speciefed interval of time, but i failed doing that.
Could anyone help me with that?
Your probably going to have to put it inside a setTimeout function like so:
var refreshId = setInterval(function() {
$.get("database.php", function(data){
var xp = data + "%";
$('#exp_bg').animate({
width: xp
}, 1500, function() { });
});
}, 1000);
This would check every second.

Categories