FlotChart Real-time load from JSON do not render - javascript

I found real-time chart (flotcharts.org). Now I tried implemented load of data from JSON file.
Data in the file are (for y axis).
{
"data":[["1","3","5","7","9","11","2","8","6","15","3","18","14","9","51","13","6","18","16","3","15","32","17","11","1","23","5","17","9","1"]]
}
HTML and jQuery function are from example. I tried edit for ajax. Data for x axis I want to generate using variable i (below in the code).
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Flot Examples: Real-time updates</title>
<link href="http://www.ondrej-vasko.cz/realtime/css/examples.css" rel="stylesheet" type="text/css">
<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../../excanvas.min.js"></script><![endif]-->
<script language="javascript" type="text/javascript" src="http://www.ondrej-vasko.cz/realtime/js/jquery.js"></script>
<script language="javascript" type="text/javascript" src="http://www.ondrej-vasko.cz/realtime/js/jquery.flot.js"></script>
<script type="text/javascript">
$(function() {
// We use an inline data source in the example, usually data would
// be fetched from a server
var data = [],
totalPoints = 300;
function getRandomData() {
$.ajax({
url: "http://www.ondrej-vasko.cz/realtime/js/data_2.json",
type: "POST",
dataType: "json"
}).success(function(data){
//$('#placeholder').append(JSON.stringify(data) + '</br>');
data.push(data);
});
return false;
// if (data.length > 0)
// data = data.slice(1);
// Do a random walk
// while (data.length < totalPoints) {
// var prev = data.length > 0 ? data[data.length - 1] : 50,
// y = prev + Math.random() * 10 - 5;
//
// if (y < 0) {
// y = 0;
// } else if (y > 100) {
// y = 100;
// }
// data.push(y);
// }
// Zip the generated y values with the x values
var res = [];
for (var i = 0; i < data.length; ++i) {
res.push([i, data[i]])
}
return res;
}
// Set up the control widget
var updateInterval = 30;
$("#updateInterval").val(updateInterval).change(function () {
var v = $(this).val();
if (v && !isNaN(+v)) {
updateInterval = +v;
if (updateInterval < 1) {
updateInterval = 1;
} else if (updateInterval > 2000) {
updateInterval = 2000;
}
$(this).val("" + updateInterval);
}
});
var plot = $.plot("#placeholder", [ getRandomData() ], {
series: {
shadowSize: 0 // Drawing is faster without shadows
},
yaxis: {
min: 0,
max: 100
},
xaxis: {
show: false
}
});
function update() {
plot.setData([getRandomData()]);
// Since the axes don't change, we don't need to call plot.setupGrid()
plot.draw();
setTimeout(update, updateInterval);
}
update();
// Add the Flot version string to the footer
$("#footer").prepend("Flot " + $.plot.version + " – ");
});
</script>
<div id="header">
<h2>Real-time updates</h2>
</div>
<div id="content">
<div class="demo-container">
<div id="placeholder" class="demo-placeholder"></div>
</div>
<p>You can update a chart periodically to get a real-time effect by using a timer to insert the new data in the plot and redraw it.</p>
<p>Time between updates: <input id="updateInterval" type="text" value="" style="text-align: right; width:5em"> milliseconds</p>
</div>
<div id="footer">
Copyright Β© 2007 - 2013 IOLA and Ole Laursen
</div>
After my editing do not work drawing data to graph. Can ask for help? Thanks

I think the problem might be when you are pushing the data after the ajax call. Put an alert in the loop that returns "res" and make sure the data is in the correct format.
var res = [];
for (var i = 0; i < data.length; ++i) {
res.push([i, data[i]])
*add Alert Here*
}
Have a look at this example. http://jsfiddle.net/grgesxbt/3/

Numerous problems at a quick glance:
1.) This:
var res = [];
for (var i = 0; i < data.length; ++i) {
res.push([i, data[i]])
}
Needs to be in the .success callback function. The way you have it now it'll execute before the AJAX call completes and data will still be []. Actually, you have a random return false; in there, so you never even hit the above code.
2.) Your AJAX return is an object with a "data" property that's an array of array of strings. You then push this into another array. Very convoluted. Rewrite the .success callback to be something like this:
.success(function(data){
var array = data['data'][0];
var res = [];
for (var i = 0; i < array .length; ++i) {
res.push([i, parseFloat(array[i])])
}
return res;
});
3.) Notice the parseFloat above, that's important. Your numbers are strings and flot won't like that. That converts them to numeric data. It would be better to fix your JSON file, then get rid of the parseFloat. Actually if you can edit the JSON file, you can make it simply:
[1,3,5,7,9,11,2,8,6,15,3,18,14,9,51,13,6,18,16,3,15,32,17,11,1,23,5,17,9,1]
Then your .success callback becomes:
.success(function(data){
var res = [];
for (var i = 0; i < data.length; ++i) {
res.push([i, data[i]])
}
return res;
});

Related

JQuery/JS script not running in html (works in Codepen)

I'm trying to make a decoding effect and I have found useful stack overflow questions to help with that but I am facing a weird problem. I have an example that I got from a stack overflow link(answer by Flambino) and it works perfectly fine. However, when I put it in my html files and test it locally, it doesn't do anything(no decoding effect). My local code from these html files are below.
html,
head,
body {
width: 100%;
margin: 0;
background-color: rgb(38, 64, 185);
}
* {
font-family: 'Whitney', sans-serif;
box-sizing: border-box;
}
div.mainContent {
margin-top: 100px;
}
span.morphText {
color: white;
}
.code {
color: red;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/mainStyles.css">
<link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght#0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<meta charset="utf-8">
<script type="text/javascript">
jQuery.fn.decodeEffect = (function($) {
var defaultOptions = {
duration: 3000,
stepsPerGlyph: 10,
codeGlyphs: "ABCDEFGHIJKLMNOPQRSTUWVXYZ1234567890",
className: "code"
};
// get a random string from the given set,
// or from the 33 - 125 ASCII range
function randomString(set, length) {
console.log("ues");
var string = "",
i, glyph;
for (i = 0; i < length; i++) {
console.log("ues");
glyph = Math.random() * set.length;
string += set[glyph | 0];
}
return string;
}
// this function starts the animation. Basically a closure
// over the relevant vars. It creates a new separate span
// for the code text, and a stepper function that performs
// the animation itself
function animate(element, options) {
var text = element.text(),
span = $("<span/>").addClass(options.className).insertAfter(element),
interval = options.duration / (text.length * options.stepsPerGlyph),
step = 0,
length = 0,
stepper = function() {
if (++step % options.stepsPerGlyph === 0) {
length++;
element.text(text.slice(0, length));
}
if (length <= text.length) {
span.text(randomString(options.codeGlyphs, text.length - length));
setTimeout(stepper, interval);
} else {
span.remove();
}
};
element.text("");
stepper();
}
// Basic jQuery plugin pattern
return function(options) {
options = $.extend({}, defaultOptions, (options || {}));
return this.each(function() {
animate($(this), options);
});
};
}(jQuery));
$("#sometext").decodeEffect();
</script>
</head>
<body>
<div class="mainContent">
<span id="sometext" class="morphText">
Hello, world
</span>
</div>
</body>
</html>
You should wrap your js code in $(document).ready so your code will run as soon as DOM becomes safe for manipilation (check this in documentation - https://api.jquery.com/ready/).
so your code will be next:
$( document ).ready(function() {
jQuery.fn.decodeEffect = (function($) {
var defaultOptions = {
duration: 3000,
stepsPerGlyph: 10,
codeGlyphs: "ABCDEFGHIJKLMNOPQRSTUWVXYZ1234567890",
className: "code"
};
// get a random string from the given set,
// or from the 33 - 125 ASCII range
function randomString(set, length) {
console.log("ues");
var string = "",
i, glyph;
for (i = 0; i < length; i++) {
console.log("ues");
glyph = Math.random() * set.length;
string += set[glyph | 0];
}
return string;
}
// this function starts the animation. Basically a closure
// over the relevant vars. It creates a new separate span
// for the code text, and a stepper function that performs
// the animation itself
function animate(element, options) {
var text = element.text(),
span = $("<span/>").addClass(options.className).insertAfter(element),
interval = options.duration / (text.length * options.stepsPerGlyph),
step = 0,
length = 0,
stepper = function() {
if (++step % options.stepsPerGlyph === 0) {
length++;
element.text(text.slice(0, length));
}
if (length <= text.length) {
span.text(randomString(options.codeGlyphs, text.length - length));
setTimeout(stepper, interval);
} else {
span.remove();
}
};
element.text("");
stepper();
}
// Basic jQuery plugin pattern
return function(options) {
options = $.extend({}, defaultOptions, (options || {}));
return this.each(function() {
animate($(this), options);
});
};
}(jQuery));
$("#sometext").decodeEffect();
});
when you call it in head element $("#sometext") is not yet available, move it to the bottom of body
<body>
<div class="mainContent">
<span id="sometext" class="morphText">
Hello, world
</span>
</div>
<script>
$("#sometext").decodeEffect();
</script>
</body>

Freely write in URL box without refreshing the page or changing domain

I'm working on a art project about poetry, writing processes and A.I (you can see the ongoing tests here http://82.223.18.239/writing3.php) and I would like to implement a thing I saw on some other website, for exemple here constantdullaart.com/
For exemple I have now : http://82.223.18.239/writing3.php (this is a temporary URL) and I would like to expend the writing to the url box (The after domain part of course). A short looped text could be constantly writen there, or a serie of symbols like on Dullaart website.
I know it can sound technically messy and not elegant at all but, still do you have any idea how to do it ?
Here's our actual code
<head>
<div id="header"></div>
<div id="body"></div>
<div id="footer"></div>
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<style type="text/css">
#myTable{
width:"90%";
height:"100%";
overflow:hidden;
min-width:250px;
white-space: pre-wrap;
word-wrap:break-word;
position:absolute;
border:solid 0px;
top:-500px;
left:320px;
right:320px;
bottom:0px;
font-size:100px;
font-family:"Times New Roman", Times, serif;
text-align:left
}
#body{
height:"100%";
overflow:auto;
min-width:250px;
}
::-webkit-scrollbar {display: none;}
</style>
</head>
<body>
<div id="myTable"> <div>
<script type="text/javascript">
var skip = 0;
function get_data(index) {
$.ajax({
url : 'getData.php',
type : 'POST',
data: ({"skip":skip}),
success : function(data) {
if(data && data.trim()!='') {
skip = skip+1;
showText("#myTable", data, 0, 20);
}
else {
setTimeout(function () { get_data(skip); }, 30000);
}
},
error : function(request,error)
{
alert("Request error : "+JSON.stringify(request));
}
});
}
function showText(target, message, index, interval) {
if (index < message.length) {
$(target).append(message[index++]);
setTimeout(function () { showText(target, message, index, interval); }, interval);
$('#myTable').css('overflow', 'hidden').bind('DOMNodeInserted', function () {
this.scrollTop = this.scrollHeight;
});
}
else {
get_data(skip);
$('#myTable').css('overflow', 'scroll')
}
}
//var period = 10000; //NOTE: period is passed in milliseconds
get_data(skip);
//setInterval(page_refresh, period);
</script>
</body>
This whole function and piece of code can be found in the page source. In Google chrome or your favorite web browser right click and select "view page source". You will find this function which does what you want:
<SCRIPT LANGUAGE="JavaScript">
var message = new Array();
message[0] = ""
var reps = 2;
var speed = 666;
var p = message.length;
var T = "";
var C = 0;
var mC = 0;
var s = 0;
var sT = null;
if (reps < 1) reps = 1;
function doIt() {
T = message[mC];
A();
}
function A() {
s++;
if (s > 8) { s = 1;}
if (s == 1) { document.title = '✊🏻✊✊🏼✊✊🏽✊✊🏾✊✊🏿✊✊🏻✊✊🏼✊✊✊🏻✊✊🏼✊✊🏽✊✊🏾'+T+'✊🏻✊✊🏼✊✊🏽✊✊🏾✊✊🏿✊✊🏻✊✊🏼✊✊🏽✊✊🏾✊✊'; }
if (s == 2) { document.title = '☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠'+T+'☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️☠️'; }
if (s == 3) { document.title = '🌍🌎🌍🌎🌍🌎🌏🌍🌎🌍🌎🌍🌎🌏🌍🌎🌍🌎🌍🌎🌏'+T+'✊🏻✊✊🏼✊✊🏽✊✊🏾✊✊🏿✊✊🏻✊✊🏼✊✊'; }
if (s == 4) { document.title = '✊🏻✊✊🏼✊✊🏽✊✊🏾✊✊🏿✊✊🏻✊✊🏼✊✊🏽✊✊🏾✊✊'+T+'β›”β›”β›”β›”β›”β›”β›”β›”β›”β›”β›”β›”β›”β›”β›”β›”β›”β›”β›”β›”'; }
if (s == 5) { document.title = 'πŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”Œ'+T+'πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› πŸ› '; }
if (s == 6) { document.title = 'πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£πŸ’£'+T+'πŸ––πŸ––πŸΏπŸ––πŸ––πŸΌπŸ––πŸΎπŸ––πŸΌπŸ––πŸΏπŸ––πŸ––πŸΌπŸ––πŸΎπŸ––πŸ––πŸΏπŸ––πŸ––πŸΌπŸ––πŸΎπŸ––πŸΌ'; }
if (s == 7) { document.title = 'πŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”Œ'+T+'πŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”ŒπŸ”Œ'; }
if (s == 8) { document.title = '✊🏻✊✊🏼✊✊🏽✊✊🏾✊✊🏿✊✊🏻✊✊🏼✊✊🏽✊✊🏾✊✊🏿'+T+'⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳'; }if (C < (8 * reps)) {
sT = setTimeout("A()", speed);
C++;
}
else {
C = 0;
s = 0;
mC++;
if(mC > p - 1) mC = 0;
sT = null;
doIt();
}
}
doIt();
(function() {
var template = 'βœŠβ˜”β˜β˜β˜β˜ β›”β˜β˜β˜β³β˜”βš β˜β˜β›”β³β˜ β˜β˜β˜β˜β˜πŸ’£βœŠπŸΎ'.split(''),
len = template.length,
chars, string, i, j, k,
pushOrHash = typeof window.history.pushState === 'function',
increase = function(n) {
return n < len - 1 ? n + 1 : 0;
},
update = function() {
chars = [];
j = k;
for (i=0; i<len; i++) {
j = increase(j);
chars[i] = template[j];
}
string = ['/', chars.join(''), '/'].join('');
k = increase(k);
if (pushOrHash) {
window.history.pushState(null, null, string);
} else {
window.document.location.hash = string;
}
setTimeout(update, 1000);
};
update();
})();
</script>
<script type="text/javascript">
function pageLoad()
{
alert('The image of external things possesses for us the ambiguous dimension that in external nature everything can be considered to be connected, but also as separated. The uninterrupted transformations of materials as well as energies brings everything into relationship with everything else and make one cosmos out of all the individual elements. On the other hand, however, the objects remain banished in the merciless separation of space; no particle of matter can share its space with another and a real unity of the diverse does not exist in spatial terms. And, by virtue of this equal demand on self-excluding concepts, natural existence seems to resist any application of them at all. Only to humanity, in contrast to nature, has the right to connect and separate been granted, and in the distinctive manner that one of these activities is always the presupposition of the other. By choosing two items from the undisturbed store of natural things in order to designate them as -separate-, we have already related them to one another in our consciousness, we have emphasized these two together against whatever lies between them. And conversely, we can only sense those things to be related which we have previously somehow isolated from one another; things must first be separated from one another in order to be together. Practically as well as logically, it would be meaningless to connect that which was not separated, and indeed that which also remains separated in some sense. The formula according to which both types of activity come together in human undertakings, whether the connectedness or the separation is felt to be what was naturally ordained and the respective alternative is felt to be our task, is something which can guide all our activity. In the immediate as well as the symbolic sense, in the physical as well as the intellectual sense, we are at any moment those who separate the connected or connect the separate. Georg Simmel from -Bridges and Doors- 1909ΜΏ');
}
pageLoad();
</script>

How to copy one image using JavaScript for one HTML5 animation,?

I have this simple code for one graphic in real time, where I can easily copy this "animation canvas" from HTML5 (id="smoothchartshowAnalisys") to a new < DIV > (id="placeholder"),
This is my goal!
And, I would like it to be automated**!
But, when I put the code into the $(function() the following error appears in my console browser's inspector:
jikken.html:264 Uncaught TypeError: Cannot read property 'getContext'
of null
(in this line var context = smoothchartshowAnalisys.getContext('2d');)
PLEASE thake a look at this jsfidle example the buttons are not working well here, but localy they are OK...
<html>
γ€€<meta charset="utf-8">
<script language="javascript" type="text/javascript" src="./assets/js/jquery.js"></script>
<script language="javascript" type="text/javascript" src="./assets/js/jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="./assets/js/jquery.flot.symbol.js"></script>
<body>
<div id="frame01" class="frame01" >
<div id="graph001" class="graph001" >
<div id="placeholder" class="flot-base" style='height:230px; width: 800px;'>
</div >
</div>
<button onclick="analysis()" class="btn btn-success" style='position:absolute; left:700px; top:226px; backgroundd:#01DF01; colorr:white'> <!-- i class="fa fa-forward"></i --> analysis </button>
<canvas id="smoothchartshowTimeLine01" style='position:absolute; left:404px; top: 100px; border:solid 1px orange; padding:0px; margin:0px; ' width="800" height="250"></canvas>
</div>
<script>
$(function() {
// Grid Lines
function seriesData1GridLines() {
if (data1.length > 0)
data1 = data1.slice(1);
// Zip the generated y values with the x values
var res = [];
for (var i = 0; i < data1.length; ++i) {
res.push([i, data1[i]])
}
return res;
}
// Heart beat wave
function seriesData2HeartBet() {
if (data2.length > 0)
data2 = data2.slice(1);
while (data2.length < totalPoints) {
// Heart beat wave
waveHeartBeatNormal();
totalPointsCtrl++
if(totalPointsCtrl>50){//784
totalPointsCtrl=1
}
}
// Zip the generated y values with the x values
var res = [];
for (var i = 0; i < data2.length; ++i) {
res.push([i, data2[i]])
}
return res;
}
// FLAG wave
function seriesData3Flag() {
if (data3.length > 0)
data3 = data3.slice(1);
if (data3b.length > 0)
data3b = data3b.slice(1);
// Zip the generated y values with the x values
var res = [];
for (var i = 0; i < data3.length; ++i) {
res.push([i, data3[i], data3b[i],])
}
return res;
}
var plot = $.plot("#placeholder", [
{data: seriesData1GridLines()},
{data: seriesData2HeartBet(),},
{data: seriesData3Flag(),},
], {
});
// the code for copy the image
// this one is NOT working !!
var smoothchartshowAnalisys = document.querySelector('#smoothchartshowAnalisys');
var smoothchartshowTimeLine01 = document.querySelector('#smoothchartshowTimeLine01');
var context = smoothchartshowAnalisys.getContext('2d');
var image = context.getImageData(0, 0, smoothchartshowAnalisys.width, smoothchartshowAnalisys.height);
smoothchartshowTimeLine01.getContext('2d').putImageData(image, 0, 0);
//
//
function update() {
plot.setData([
{data: seriesData1GridLines(), points: {show: false}, lines: {show: true},},
{data: seriesData2HeartBet(), points: {show: false}, lines: {show: true},},
{data: seriesData3Flag(), points: {show: true}, lines: {show: true},}
]);
plot.draw();
realTime = setTimeout(update, updateInterval);
}
update();
});
//
// copying the image from canvas when press a button
// this one is working !!
function analysis() {
var placeholder = document.querySelector('.flot-base');
var smoothchartshowAnalisys = document.querySelector('#smoothchartshowAnalisys');
var context = placeholder.getContext('2d');
var image = context.getImageData(0, 0, placeholder.width, placeholder.height);
smoothchartshowAnalisys.getContext('2d').putImageData(image, 0, 0);
}
//
// the waves
//
function waveHeartBeatNormal() {
// heart beat wave
}
</script>
</body>
</html>*
So, My question is:
how to make that < div > always up to date? automaticaly?
thanks

Clone HTML elements with JS

Trying to set up a Tic-Tac-Toe board based on JS input with an alert. The alert never shows up, and the HTML is never rendered... what am I missing?
ALL HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Tic Tac Toe! (and more...)</title>
<meta name="description" content="Tic Tac Toe">
<meta name="author" content="SinSysOnline">
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js.js"></script>
<style>
body{
font-family:"Lucida Console", Monaco, monospace;
}
td{
border-right:1px solid #000;
border-bottom:1px solid #000;
width:100px;
height:100px;
text-align:center;
font-size:72px;
}
td:last-child{
border-right:none;
border-bottom:1px solid #000;
}
tr:last-child td{
border-bottom:none;
}
</style>
</head>
<body>
<div id="dashboard">
<input type="text" value="How large is your grid? (default 3)" size="35" />
</div>
<table id="board">
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</body>
</html>
ALL JS (minus jQuery)
/* Sadly, there is a very well known algorithm to ensure one NEVER loses at
tic-tac-toe. Ties, perhaps, but if you play right you can NEVER LOSE.
I will not institue this cheap shot into my program, and this will be
a computer vs you. I will add in potential moves :-) */
(function($) {
function create(x){
var board = [];
for(var i=0;i<x;i++){
var tempArr = [];
for(var j=0;j<x;j++){ tempArr[j] = ""; }
board.push(tempArr);
}
$('#board tr').clone(x);
return board;
}
var x = prompt("How large would you like your grid? (3-10)");
var board = create(x);
})(jQuery);
I've tried adding the JS to the bottom of my body... just kind of confused here. I know JS inside and out... except for DOM manipulation...
you didn't do any thing with your cloned element!
if you want to dynamically generate a table
the code should be like this
var $board = $('#board');
var td = "<td></td>", $tr = $("<tr></tr>");
function create(x) {
$board.empty();
var arr = [];
for(var i = 0; i < x; i++) {
arr.push(td);
}
var $trCloned = $tr.clone().append(arr.join(''));
for(var j = 0; j < x; j++) {
$board.append($trCloned);
}
}
Here is the fiddle
// JQuery
function create(board, x)
{
var row = $("<tr></tr>");
var i;
for (i = 0; i != x; i++) row.append ($("<td>x</td>")); // create a row
for (i = 0; i != x; i++) $('#'+board).append(row.clone()); // then the board
}
// sample use
var x = window.prompt ("How much, boss?");
create('board', x);
// html
<table id='board' />
I've put an 'x' inside the cells so that the board is visible
As Fiddle works, this No-Prompt problem is more like an environment/compatibility/typo issue. The problem can be solved progressively.
There is a misuse of jQuery's clone() function, the clone() function accepts boolean type (http://api.jquery.com/clone/) , which means whether or not event handlers will be copied. From the code I guess this is not what you want. Please correct it and try again.
On which browser did you test? Does this issue happen on one specific browser, or happens on all browsers in your computer? If it is the latter one, then copy your code (copy the files, not re-type) to someone else' computer and try again.
Simplify the JS code and test step by step. First, just leave the prompt() line and delete all else, will it work? Then, add an empty create() function and try again. Then, add something more. Sooner or later, you will find the line which causes the problem.
Please let us know if you deliver the above experiment and find something new.
EDITS
I'll never stop if I don't stop now. I'm stuck anyway. Hope this helps you on your way. Still needs some work (undefined references) but is functional if my fanciness didn't distract me so much:
JS Fiddle Demo (not working)
Javascript:
(function (window, document, $) {
var $board = $('#board');
var x = parseInt(prompt("How large would you like your grid? (3-10)"), 10);
var taken = [];
create(x);
function create(x) {
var tmp;
var $tr = $('<tr/>');
var $td = $('<td/><td/><td/>');
if (x <= 10 && x >= 3 && typeof x === 'number') {
for (var i = 0; i < x; i++) {
tmp = $tr.append($td);
tmp.clone().appendTo($board);
}
$('#board').on('click', 'td', function (evt) {
var e = evt || window.event;
var y = $(this).index();
var z = $(this).parent('tr').index();
taken = (!taken) ? [y, z] : taken;
userChoice(y, z, x, this);
});
} else {
alert('You entered an incorrect value. Try again!');
return false;
}
}
function userChoice(y, z, x, el) {
//if($(el).text() !== "") {
console.log(taken);
for (var d = 0; d < (x - 1); d++) {
for (var o = 0, n = 0; o < 3; o++) {
if ((taken[n].indexOf(y) && taken[n].indexOf(z)) || (taken[n].indexOf(y) && taken[n].indexOf(z))) {
alert('Already played that spot. Nice try.');
return false;
}
n++;
}
}
taken.push([y, z]);
$(el).text('O');
console.log(taken);
if ((taken.length * taken[taken.length].length) / (x - 1) === 3) {
alert('No more spaces! Game over!');
return false;
}
compChoice(x);
}
function compChoice(x) {
console.log(taken);
var a = Math.floor(Math.random(10) * x);
var b = Math.floor(Math.random(10) * x);
for (var d = 0; d < (x-1); d++) {
for (var o = 0, n = 0; o < 3; o++) {
if ((taken[n].indexOf(a) && taken[n].indexOf(b)) || (taken[n].indexOf(a) && taken[n].indexOf(b))) {
compChoice(x);
}
n++;
}
}
taken.push([a,b]);
console.log(taken);
$board.find('tr:nth-of-type(' + a + ')').find('td:nth-of-type(' + b + ')').text('X');
if ((taken.length * taken[taken.length].length) === x) {
alert('No more spaces! Game over!');
return false;
}
}
})(this, this.document, jQuery, undefined);
HTML:
<div id="dashboard">
<noscript>
<input type="text" value="How large is your grid? (default 3)" size="35" />
</noscript>
</div>
<table id="board"></table>

Error $.get(...).done is not a function

I have code that looks like that:
<head>
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript">
function draw(){
var a = 0,
timeC = 0,
timeS = 0,
meanCFf=0,
meanSFf= 0;
$.get('test1.csv').done(function(data) {
var i,
lines = data.split('\n'),
line = lines[0].split(','),
oS = line.indexOf('oS'),
browName = line.indexOf('browName'),
browVer = line.indexOf('browVer'),
timeCanvas = line.indexOf('timeCanvas'),
timeSvg = line.indexOf('timeSvg');
for(i=1; i<lines.length; i++) {
line = lines[i].split(',');
if(line[oS] === 'Windows') {
a++;
timeC += parseFloat(line[timeCanvas], 10);
timeS += parseFloat(line[timeSvg], 10);
}
}
});
meanCFf = timeC/a;
meanSFf = timeC/a;
var os1 = document.getElementById("osInfo1");
os1.innerHTML = "Twoja Ε›rednia to: " + meanCFf;
var os2 = document.getElementById("osInfo2");
os2.innerHTML = "TwΓ³j sytem operacyjny to: " + meanSFf;
}
</script>
</head>
<body onload="draw()">
<p id="osInfo1"></p>
<p id="osInfo2"></p>
</body>
And I get an error Unhandled Error: '$.get('test1.csv').done' is not a function, I tried to google this error but I don't understand the answer its some kind of name problem?? From what i googled I tried to change $ for jQuery but still got the same error
The .done() was introduced in jQuery 1.5. You seem to be using jquery 1.3. So make sure that you upgrade to jQuery 1.5 if you want to use deferred objects.
If for some reason you cannot upgrade you could use the success callback of the $.get function:
$.get('test1.csv', function(data) {
var i,
lines = data.split('\n'),
line = lines[0].split(','),
oS = line.indexOf('oS'),
browName = line.indexOf('browName'),
browVer = line.indexOf('browVer'),
timeCanvas = line.indexOf('timeCanvas'),
timeSvg = line.indexOf('timeSvg');
for(i = 1; i < lines.length; i++) {
line = lines[i].split(',');
if(line[oS] === 'Windows') {
a++;
timeC += parseFloat(line[timeCanvas], 10);
timeS += parseFloat(line[timeSvg], 10);
}
}
});
You have used old jquery, Try using latest jquery version
The jquery version you used is too low, please use higher jquery version run your code.

Categories