A while ago, I created (with much help) a program that uses php and javascript to make some ambient music by randomizing an array of .ogg files. Now I am trying to re-write it with js alone.
The new code immediately below does not work (the .ogg files do play properly when clicked individually, but nothing happens when you press the 'start' button, which is the main feature). (The code below that (containing php) does work.) I've been over the new code several times and I think I've got the 'typos'. I'm pretty sure the problem is in the syntax of the window.setTimeout line, but haven't quite figured out how it should be.
Thanks for any help you can offer!
<!DOCTYPE html>
<html>
<head>
<title>Audio Testing</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function getRandInt (min, max)
{
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function shuffle(o)
{
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
</script>
<script type="text/javascript">
var tonesTotal = 150;
function getDelays(tonesTotal)
{
var return_array = array();
for (var i = 0; i < tonesTotal; i++)
{
var r = getRandInt(0, 600);
var delay = r * 1000;
return_array.push(delay);
}
return return_array;
}
var delays = new Array();
delays = getDelays(tonesTotal);
$(document).ready(function()
{
$("#start").click(function()
{
var base = 'sound';
for(var i = 0; i < tonesTotal; i++)
var id = base + ((i + 1) );
window.setTimeout ("document.getElementById('" + id + "').play()", delays[i]);
});
});
</script>
</head>
<body style="background-color: #999;">
<button id="start">Start</button>
<br><br>
<script>
var tonesTotal = 150;
var samples = new Array("tone0.ogg", "tone2.ogg", "tone4.ogg", "tone6.ogg", "tone7.ogg", "tone9.ogg", "tone11.ogg", "tone12.ogg");
for (var i=1; i <= tonesTotal; i++)
{
shuffle (samples);
var samplepick = samples[0];
document.write ("<audio controls id='sound" + i + "'><source src='" + samplepick + "' type='audio/ogg'></audio>");
}
</script>
</body>
</html>
PREVIOUS CODE:
<!DOCTYPE html>
<html>
<head>
<title>Audio Testing</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<?php
//$randC = rand(1,4);
$C = 150;
function getDelays($C)
{
$return_array = array();
for($i = 0; $i < $C; $i++)
{
$r = rand(0, 600);
$delay = $r * 1000;
array_push($return_array, $delay);
}
return $return_array;
}
echo "<script type=\"text/javascript\">\n";
echo "var delays = new Array();";
$delays = getDelays($C);
for($i = 0; $i < sizeof($delays); $i++)
{
echo "delays[" . $i . "] = " . $delays[$i] . ";\n";
}
echo "
$(document).ready(function()
{
$(\"#start\").click(function()
{
var base = 'sound';
for(i = 0; i < $C; i++)
{
var id = base + ((i + 1) );
window.setTimeout (\"document.getElementById('\" + id + \"').play()\", delays[i]);
}
});
});
</script>
";
?>
<style type="text/css">
</style>
</head>
<body style="background-color: #999;">
<button id="start">Start</button>
<br><br>
<?php
$samples = array("tone0.ogg", "tone2.ogg", "tone4.ogg", "tone6.ogg", "tone7.ogg", "tone9.ogg", "tone11.ogg", "tone12.ogg");
for ($i=1; $i<= $C; $i++) {
shuffle ($samples);
$samplepick = $samples[0];
echo '<audio controls id="sound'.$i.'">
<source src='.$samplepick.' type="audio/ogg">
</audio>';
}
?>
</body>
</html>
When I tested it locally I found a Javascript error in the getDelays() function: First line of code should be:
var return_array = new Array();
Related
Below is my Puzzle image code. I have getting only one image because of onload function so please suggest me to getting more image
this file is include in my main html code but one Image will be displayed and another is display NULL
<html>
<head>
<title>HTML5 Puzzle Game</title>
<script type="text/javascript">
window.onload = onReady;
var can;
var ctx;
var img;
var clickX;
var clickY;
var selected1;
var selected2;
var blockSize = 160;
var piecesArray = new Array();
function onReady()
{
can = document.getElementById('myCanvas');
ctx = can.getContext('2d');
img = new Image();
img.onload = onImage1Load;
img.src = "images/<?php echo $crows['product_image1']; ?>";
}
function onImage1Load()
{
var r;
for(var i = 0; i < 4; i++)
{
for(var j = 0; j < 3; j++)
{
r = new Rectangle(i * blockSize, j * blockSize, i*blockSize + blockSize, j * blockSize + blockSize);
piecesArray.push(r);
}
}
scrambleArray(piecesArray, 30);
drawImage();
}
function Rectangle(left, top, right, bottom)
{
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
this.width = right - left;
this.height = bottom - top;
}
function scrambleArray(ar, times)
{
var count = 0;
var temp;
var index1;
var index2;
while(count < times)
{
index1 = Math.floor(Math.random()*piecesArray.length);
index2 = Math.floor(Math.random()*piecesArray.length);
temp = piecesArray[index1];
piecesArray[index1] = piecesArray[index2];
piecesArray[index2] = temp;
count++;
}
}
function drawImage()
{
var r;
for(var i = 0; i < 4; i++)
{
for(var j = 0; j < 3; j++)
{
r = piecesArray[i*3+j];
ctx.drawImage(img, r.left, r.top, r.width, r.height, i*blockSize, j*blockSize, blockSize, blockSize);
ctx.strokeStyle = "#fff";
}
}
}
function highlightRect(drawX, drawY)
{
ctx.beginPath();
ctx.moveTo(drawX, drawY);
ctx.lineTo(drawX + blockSize, drawY);
ctx.lineTo(drawX + blockSize, drawY + blockSize);
ctx.lineTo(drawX, drawY + blockSize);
ctx.lineTo(drawX, drawY);
ctx.lineWidth = 2;
// set line color
ctx.strokeStyle = "#fff";
ctx.stroke();
}
function swapRects(r1, r2)
{
var index1;
var index2;
var temp = r1;
index1 = piecesArray.indexOf(r1);
index2 = piecesArray.indexOf(r2);
piecesArray[index1] = r2;
piecesArray[index2] = temp;
}
function onCanvasClick(evt)
{
clickX = evt.offsetX;
clickY = evt.offsetY;
var drawX = Math.floor(clickX / blockSize);
var drawY = Math.floor(clickY / blockSize);
var index = drawX * 3 + drawY;
var targetRect = piecesArray[index];
var drawHighlight = true;
drawX *= blockSize;
drawY *= blockSize;
ctx.clearRect(0, 0, 640, 480);
if(selected1 != undefined && selected2 != undefined)
{
selected1 = selected2 = undefined;
}
if(selected1 == undefined)
{
selected1 = targetRect;
}
else
{
selected2 = targetRect;
swapRects(selected1, selected2);
drawHighlight = false;
}
drawImage();
if(drawHighlight)
highlightRect(drawX, drawY);
}
</script>
</head>
<body>
<div style="margin:0 auto; width:640px; height:480px; border: 4px none #cc6699;">
<canvas id="myCanvas" width="640" height="480" onclick="onCanvasClick(event);" style="border:1px dotted #fff;">
</canvas>
</div>
</body>
</html>
My phpcode is
<?php for($i = 1; $i < 5; $i++) { ?>
<div class="upperBoxContainer" id="test1<?php echo $i; ?>">
<img id="test<?php echo $i; ?>" src="images/midimages/<?php echo $i; ?>.jpg">
</div>
<?php } ?>
And my javascript code is
jQuery(document).ready(function() {
for (var i = 1; i < 5; i++) {
alert('images/midimageshover/' + i + '.jpg');
$('#test1' + i).hover(function() {
$('#test' + i).attr('src', 'images/midimageshover/' + i + '.jpg');
});
$('#test1' + i).mouseout(function() {
$('#test' + i).attr('src', 'images/midimages/' + i + '.jpg');
});
}
});
There is some error due to this code is not work. can you please find this.
Thanks in advance
Enclose your events in a Immediately-Invoked Function Expression (IIFE)
jQuery(document).ready(function(){
for (var i = 1; i < 5; i++) {
(function(i){
$('#test1'+i).hover(function(){
$('#test' + i).attr('src', 'images/midimageshover/' + i + '.jpg');
});
$('#test1'+i).mouseout(function(){
$('#test' + i).attr('src', 'images/midimages/' + i + '.jpg');
});
})(i);
}
});
Your code is rewriting the value of $('#test1'+i) until it reaches 4, so at the end of the loop you'll only have $('#test14').
The code above create different scope by using the IIFE hence $('#test1'+i) won't be overwritten, instead you'll have $('#test11'), $('#test12'), $('#test13'), $('#test14')
Here is a demo to demonstrate the difference with your initial code
I was working with html5 slice and webworker but when it goes to uploadFile function, nothing happened. nothing being upload
<html>
<head>
<title>Upload Files using XMLHttpRequest</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
</head>
<body>
<form id="fileuploader" enctype="multipart/form-data" method="post" action="upload.php">
<label for="fileToUpload">Select Files to Upload</label><br />
<input type="file" name="fileToUpload[]" multiple="" id="fileToUpload" onchange="fileList();"/><br />
<input type="button" onclick="sendRequest();" value="Upload" />
<!-- a place for File Listing -->
<div id="fileList">
</div>
</form>
</body>
</html>
<script type="text/javascript">
function sendRequest() {
var worker = new Worker("fileupload.js");
worker.onmessage = function(e) {
alert(e.data);
}
var file = document.getElementById('fileToUpload');
for(var i = 0; i < file.files.length; i++) {
worker.postMessage(file.files[i]);
}
}
and for the fileupload.js
var file;
var p = true;
function uploadFile(blobFile, fileName, filePart, totalChunks) {
var xhr = new XMLHttpRequest();
xhr.open("POST", "upload.php"+"?"+"file="+fileName + filePart, true);
xhr.onload = function(e) {
};
xhr.send(blobFile);
}
function process() {
var blob = file;
var originalFileName = blob.name;
var filePart = 0
const BYTES_PER_CHUNK = 100 * 1024 * 1024; // 100MB chunk sizes.
var realFileSize = blob.size;
var start = 0;
var end = BYTES_PER_CHUNK;
totalChunks = Math.ceil(realFileSize / BYTES_PER_CHUNK);
while( start < realFileSize ) {
//self.postMessage(start);
//self.postMessage("test");
var chunk = blob.slice(start, end);
uploadFile(chunk, originalFileName, filePart, totalChunks);
filePart++;
start = end;
end = start + BYTES_PER_CHUNK;
}
}
self.onmessage = function(e) {
file = e.data;
/*for (var j = 0; j < e.data.length; j++) {
files.push(e.data[j]);
}*/
if (p) {
process();
}
}
To summarize your code:
if (!blob.webkitSlice && !blob.mozSlice) {
var chunk = blob.mozSlice(start, end);
// or: var chunk = blob.webkitSlice(start, end);
}
This is the line where you get that error from, and it should be obvious that you need to get an exception there.
Sure, for older versions of those browsers you probably should check for the prefixed functions. But if the "feature" detection has not matched, you will need to use the plain function - may it be because those vendors have dropped the prefixes, or the code is executed in some other browser (Opera, IE). See also Browser compatibility: Notes on the slice() implementations at MDN.
So, use this:
var slice = blob.webkitSlice || blob.mozSlice || blob.slice;
var chunk = slice.call(blob, start, end);
Here is a complete working code.
var file = [], p = true;
function upload(blobOrFile) {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/server', false);
xhr.onload = function(e) {
};
xhr.send(blobOrFile);
}
function process() {
for (var j = 0; j <file.length; j++) {
var blob = file[j];
const BYTES_PER_CHUNK = 1024 * 1024;
// 1MB chunk sizes.
const SIZE = blob.size;
var start = 0;
var end = BYTES_PER_CHUNK;
while (start < SIZE) {
if ('mozSlice' in blob) {
var chunk = blob.mozSlice(start, end);
} else {
var chunk = blob.webkitSlice(start, end);
}
upload(chunk);
start = end;
end = start + BYTES_PER_CHUNK;
}
p = ( j = file.length - 1) ? true : false;
self.postMessage(blob.name + " Uploaded Succesfully");
}
}
self.onmessage = function(e) {
for (var j = 0; j < e.data.length; j++)
files.push(e.data[j]);
if (p) {
process()
}
}
I have a php/javascript code that takes a GPS coordinate from an Iphone/website app (instamapper) and adds it to my website page. (using snippets of other peoples code examples so far) I'd like to change the popup from displaying the decimal coordinates to proper Lat / Long but cant quite work it out. Any help or pointers you guys could give would be great. My code is below.
found here http://www.morvargh-sailing.co.uk/tracker/test2.php
<?php
$key = "16194603621692259587";
$fichier = "http://www.instamapper.com/api?action=getPositions&key=".$key."&num=1";
$fp=#fopen($fichier,"r");
$texte = "";
if($fp)
{
while(!feof($fp))
{
$texte .= fgets($fp,1024);
}
}
$donnees = explode(',',$texte);
/*
0 : first line plus device number
1 : Device label
2. Position timestamp in UTC (number of seconds since January 1, 1970)
3. Latitude
4. Longitude
5. Altitude in meters
6. Speed in meters / second
7. Heading in degrees
*/
date_default_timezone_set('GMT');
$name = $donnees[1];
$date = date('H:i:s d-m-Y e', $donnees[2]);
$lat = $donnees[3];
$longitude = $donnees[4];
$altitude = $donnees[5];
$speed = $donnees[6];
$heading = $donnees[7];
echo('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Where am I</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAA_GqVjhr7wgurGjr_zR-wJxSbxjqNwl0XTkuBKGwUYonF3JCDWBRyXrxgjwLgrUjcet0gLjyGZOGwCA" type="text/javascript"></script>
<style type="text/css">
v\:* {behavior:url(#default#VML);}
html, body {width: 100%; height: 350px}
body, form, p {margin: 0; padding: 0; text-align:center; font-family:"lucida grande","trebuchet ms",sans-serif; font-size:12px;}
a:link, a:visited, a:hover {color: #369; background:transparent; text-decoration: none;}
#instamapper {position:absolute; left:80px; bottom:10px;}
#instamapper p {text-align:right;}
</style>
</head>
<body onLoad="showAddress(\''.$lat.', '.$longitude.'\'); return false" onunload="GUnload()">
<div id="map" style="width: 100%; height: 100%;"></div>
<div id="instamapper">
<p>
GPS tracking powered by InstaMapper
<p>
<div>
<script type="text/javascript">
//<![CDATA[
var momento = "'.$date.'";
var altitud = "'.$altitude.'" + "m";
var velocidad = "'.$speed.'" + " Km/h";
var longitude = "'.$longitude.'";
var latitude = "'.$lat.'";
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
var geocoder = new GClientGeocoder();
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
function showAddress(address) {
geocoder.getLatLng(
address,
function(point) {
if (!point) {
alert("\"" + address + "\" no encontrado");
} else {
map.setCenter(point, 12);
var marker = new GMarker(point);
var info = "<b>Last known location:</b><p>Time: " + momento + "<br>Latitude: " + latitude + "<br>Longitude: " + longitude + "<br>Heading: " + '.$heading.' +"º";
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(info);
});
map.addOverlay(marker);
marker.openInfoWindowHtml(info);
}
}
);
}
}
//]]>
</script>
</body>
</html>');
?>
Try this function: http://jsfiddle.net/eAUJr/1/
function format(newLat, newLng) {
if (newLat < 0) {
newLat = myround(Math.abs(newLat)) + "S";
} else {
newLat = myround(newLat) + "N";
}
if (newLng < 0) {
newLng = myround(Math.abs(newLng)) + "W";
} else {
newLng = myround(newLng) + "E";
}
return[newLat, newLng];
}
function myround(val) {
deg = parseInt(val);
val -= deg;
val *= 60;
min = parseInt(val);
val -= min;
val *= 60;
sec = parseInt(val);
remainder = val - sec;
if(remainder >= 0.5) {
sec += 1;
}
return deg + "°" + min + "'" + sec + '"';
}
document.write(format(-0.000277778, 20.292))
// output: 0°0'1"S,20°17'31"E
I want to implement a time counter with JavaScript or PHP. I did some looking on Google and tried it, but didn't get the output I need.
Users will enter the time in the textbox provided, then I need to give them a counter from the time they entered.
Example: If I enter 1:27:38 and click on submit, the time should decrease and I should get an alert when it reaches 0.
How can I implement this?
In JavaScript:
<html>
<head>
</head>
<body>
<script language="JavaScript">
<!-- //
var timeleft;
var nextdue;
var tick = 1000;
function parseTime(t) {
var tt = ("0:00:"+t);
tt = tt.split(":").reverse();
return (tt[0] * 1000)+(tt[1] * 60000)+(tt[2] * 3600000);
}
function zeroPad(n) {
if (n<10) return "0"+n;
return ""+n;
}
function makeTime(t) {
if (t<0) return "0:00:00";
var tt=t+999;
return Math.floor(tt/3600000)+":"+
zeroPad(Math.floor(tt/60000)%60)+":"+
zeroPad(Math.floor(tt/1000)%60);
}
function startTimer() {
nextdue = new Date().getTime();
timeleft = parseTime(document.timerform.timerbox.value);
runTimer();
}
function runTimer() {
document.timerform.timerbox.value=makeTime(timeleft);
if (timeleft<=0) alert ("Time's up!");
else {
var timecorr = (new Date().getTime())-nextdue;
if (timecorr>0 && timecorr<3000) {
timeleft -= (tick+timecorr);
nextdue += tick;
if (timeleft<1) setTimeout ("runTimer()",tick+timeleft);
else setTimeout("runTimer()",Math.max(1,tick-timecorr));
}
else {
nextdue=(new Date().getTime())+tick;
timeleft-=tick;
if (timeleft<1) setTimeout ("runTimer()",tick+timeleft);
else setTimeout("runTimer()",tick);
}
}
}
// -->
</script>
<form name="timerform">
Decimal places: <input type="text" name="timerbox" value="0:00:00"></input>
<input type="button" value="Start timer" onClick="startTimer()"></input>
</form>
</body>
</html>
In PHP:
list($hours, $minutes, $seconds) = explode(':', $_POST['time']);
$seconds = $hours * 3600 + $minutes * 60 + $seconds;
for ($i = $seconds; $i > 0; $i--)
{
echo $i;
sleep(1);
flush();
}
echo 'Countdown finished.';