I want to change the number by chooesing 6 numbers from 49 numbers, so first I declared a div and have six span in it to contain a number.
And I want to change it by getElementByTagName to assign a new number combined with setInterval to make it always changing but it doesn't work.
Where is my wrong place?
Thx.
function computeRandom(){
var value = new Array(49);//declare array
for ( i = 0; i < 49; i++ )//initial array_value
value[i] = i+1;
for ( i = 0 ;i < 100; i++ ) {//random arrange
x = parseInt(Math.random()*49);
y = parseInt(Math.random()*49);
tmp = value[x];
value[x] = value[y];
value[y] = tmp;
}
var color = new Array(49);
for ( i = 0; i < 49; i++ )//store color
color[i] = "rgb(" + parseInt(Math.random()*255) + "," + parseInt(Math.random()*255) + "," + parseInt(Math.random()*255) + ")";
var value_tmp = new Array(6);
for( i = 0; i < 6; i++)
value_tmp[i] = value[i];
document.write("<div style = \"text-align:center;\" >");//center the text by div
for( i = 0; i < 6; i++)
document.write("<span style = \"font-size: 2.5em; display:inline-block; text-align:center; width: 1.5em; background: white; color: " + color[i] + " \" > "
+ value_tmp[i] + "</span>     ");
var spanArray = document.getElementsByTagName("span");
setInterval("keepMove(value,spanArray)",10);
}
function keepMove(val,sp){
var index = parseInt(Math.random()*43);//set a increment to avoid repeatition
for( i = 0; i < sp.length; i++){
sp[i].innerHTML = val[i+index];
document.write(sp[i].innerHTML+" ");
}
}
CSS:
#bg {
background: grey;
opacity: 0.8;
}
#hl {
text-align: center;
color: white;
}
HTML:
sorry I don't know how to post the HTML?
http://codepad.org/IrSOsjg7
I have tried the commentor's advice but still not work but thx for your help!
I very appreciate it!
I think the problem is setInterval("keepMove(value,spanArray)",10)
when you pass a string as the first parameter of setInterval, it's like eval that string, and the code will run in global environment, because there is no variable value and spanArray in the global environment, the code will not run correctly.
For example:
function foo(x, y) {
alert(x + " " + y);
}
function bar() {
var x = 100, y = 200;
setInterval("foo(x, y)", 1000);
}
bar();
this will get the error x is not defined
You can try:
setInterval(function(){
keepMove(value, spanArray);
}, 10);
Try to change the way you use the setInterval. You should use a closure to be able to access the value and spanArray vars.
setInterval(function(value, spanArray) {
return function() {
keepMove(value,spanArray)
}
}(value, spanArray),10);
}
That's because setTimeout will be executed on the global context, and from there you can't access those private vars.
Related
I don't know to set [i] in the array.
statusResponse() {
var dataStatus = this.$.xhrStatus.lastResponse;
for(var i = 0; i < this.maxStatus; i++) {
console.log(this.maxStatus);
console.log([i]);
console.log(dataStatus);
console.log(dataStatus[fs_+ i +_P41001_W41001B]);
this.userInfo.status({
"branch_plant": this.$.xhrStatus.lastResponse.fs_ +
[i] +_P41001_W41001B.data.gridData.rowset[0].sDescription_99.value
});
}
}
You could change:
dataStatus[fs_+ i +_P41001_W41001B]
to
dataStatus["fs_" + i + "_P41001_W41001B"]
Explaination
This is roughly how the computer understands it the following line:
Take string "fs_"
Add the variable i to it, so the string become "fs_4" (if i = 4)
Add "_P41001_W41001B" to it, so the string becomes "fs_4_P41001_W41001B"
Get dataStatus["fs_4_P41001_W41001B"]
Updated code:
statusResponse() {
var dataStatus = this.$.xhrStatus.lastResponse;
for(var i = 0; i < this.maxStatus; i++) {
console.log(this.maxStatus);
console.log([i]);
console.log(dataStatus);
console.log(dataStatus["fs_" + i + "_P41001_W41001B"]);
this.userInfo.status({
"branch_plant": this.$.xhrStatus.lastResponse["fs_" + i + "_P41001_W41001B"].data.gridData.rowset[0].sDescription_99.value
});
}
}
I am sure this one is staring me in the face. Trying to increase the rotation on an object until i reaches a value. Getting an error as I am trying to escape the CSS part to enter my variable 'i'.
Can anybody see what may be wrong?
for(var i = 0; i < 200; i++){
console.log(i);
$('.rotateMe').css({"transform": "rotate("i"deg)"});
}
Thanks
You have to concatenate variable inside string with + , like this:
for(var i = 0; i < 200; i++){
console.log(i);
$('.rotateMe').css({"transform": "rotate("+i+"deg)"});
}
for (var i = 0; i < 200; i++) {
$('.rotateMe').css({
"transform": "rotate(" + i + "deg)"
});
}
.rotateMe {
width: 50px;
height: 50px;
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="rotateMe"></div>
You forgot the +
for(var i = 0; i < 200; i++){
console.log(i);
$('.rotateMe').css({"transform": "rotate("+i+"deg)"});
}
You cannot concatenate strings like that in JS, try
"rotate("+i+"deg)"
You have an error in your code:
for(var i = 0; i < 200; i++){
console.log(i);
$('.rotateMe').css({"transform": "rotate(" + i + "deg)"});
}
For string concatenation in javascript you must use the plus (+).
I'm new here. I have spent the entire day trying to figure out what is wrong with my code. Yes, it might be a simple questions for you, since I just started JavaSript about a month ago. Anyways, your help in identifying the error in my code is greatly appreciated!
==========================================================================
The Question:
Code a function called extremeValue. It takes 2 parameters. The first is an array of integers (you do not need to validate this). The second parameter is either the String “Minimum” or “Maximum”. The function returns the minimum or maximum element value in the array depending on the second parameter’s value.
Do not use Math.min or Math.max. The standard algorithm for finding a minimum value in an array is to assume the first element (at index 0) is the current minimum. Then process the array repetitively from its second element to its last. On each iteration compare the current element being processed with the current minimum. If it’s less than the minimum set it as the current minimum. In this way at the end of processing the current minimum holds the minimum element value in the array. A similar process will work for finding the maximum. Test your code. (1 mark)
This function does two different jobs depending on its second parameter. What are the pros and cons of this approach to coding functions?
My Answer (which doesn't work):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Eng1003 Workshop Code Week 04</title>
<style>
#outputArea{
padding: .25em;
border: solid black 2px;
margin: 3em;
height: 20em;
width: 20em;
overflow-y: scroll;
font-family: arial "sans serif";
font-size: 1em;
color: rgb(50, 50, 250);
background-color: rgb(225,225,225) ;
}
</style>
</head>
<body>
<!-- -->
<div id="outputArea"></div>
<script>
function maximum(setOfValues){
var retVal = "" ;
var length = setOfValues.length ;
var max = 0 ;
for (var i = 0; i < length; i++){
if (setOfValues[i] > max){
max = setOfValues[i] ;
}
}
retVal = max ;
return retVal ;
}
function minimum(setOfValues){
var retVal = "";
var length = setOfValues.length ;
var min = 0 ;
for (var i = 0; i < length; i++){
if (setOfValues[i] < min){
min = setOfValues[i] ;
}
}
retVal = min;
return retVal ;
}
function extremeValue(setOfValues, command){
var outString = "" ;
var retVal = "" ;
if (command = "Maximum"){
outString = "The maximum value is " + maximum(setOfValues) + "." ;
} else if (command = "Minimum"){
outString = "The minimum value is " + minimum(setOfValues) + "." ;
} else {
outString = "Sorry, but your command is unclear. Please ensure that your input is either 'Maximum' or 'Minimum'." ;
}
retVal = outString ;
return retVal ;
}
var target = document.getElementById("outputArea") ;
var inputCommand = prompt("What is your command?") ;
var inputValues = [10,30,500, 1000] ;
var finalAnswer = "" ;
finalAnswer = extremeValue(inputValues, inputCommand) ;
target.innerHTML = finalAnswer ;
</script>
</body>
The problem is the way you're checking your prompted value:
if (command = "Minimum")
if (command = "Maximum")
Here you're assigning strings to command. The code should be (assuming we're using strict equality):
if (command === "Minimum")
if (command === "Maximum")
DEMO
In you HTML page, call the Result function as below:
<script>
Result.init();
</script>
var Result = function () {
var maximum = function (array) {
var val = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] > val) {
val = array[i];
}
}
return val;
}
var minimum = function (array) {
var val = 0;
for (var i = 0; i < array.length; i++) {
val = array[i];
if (array[i] < val) {
val = array[i];
}
}
return val;
}
var start = function () {
var inputValues = [10, 30, 500, 1000];
var min = minimum(inputValues);
var max = maximum(inputValues);
}
return {
init: function () {
start();
}
};
}();
Please Look at the following code only the last image moves.
http://jsfiddle.net/u8Bg3/
But second one works
http://jsfiddle.net/u8Bg3/1/
As pointed by the Er144 even this works with jquery
http://jsfiddle.net/u8Bg3/14/
I also found out appendchild works but not innerhtml
The difference between two is that in first one html exits in second one it's dynamically created
HTML
<body>
<div class="racetrack" id="racetrack"></div>
<div id="track-tmpl" class="hide">
<div class="track"><div id="player{{ x }}" class="runner"></div></div>
</div>
</body>
JS
var position = [0,40,80,120,80],
racetrack = document.getElementById('racetrack');
track_tmpl = document.getElementById('track-tmpl').innerHTML;
function Players(ele, ptimeout)
{
this.el = ele;
this.i = 0;
this.iterations = 0;
this.stop = 0;
this.timeout = ptimeout;
this.position = 0;
this.animate = function(){
if(this.i !== 0){
this.move((this.position + 5), this.i);
}
if(!this.stop){
if(this.i < 5){
setTimeout(function(_this){
_this.i++;
_this.animate();
},this.timeout,this);
}
if(this.i==5){
this.iterations ++;
if(this.iterations < 50){
this.i = 0;
this.animate();
}
else{
this.el.style.backgroundPosition = '120px 0px';
}
}
}
};
this.start = function(){
this.stop = 0;
this.animate();
};
this.move = function(to,positionIndex){
this.position = to;
this.el.style.backgroundPosition = '-'+position[positionIndex]+'px 0px';
this.el.style.webkitTransform = 'translate('+to+'px)';
this.el.style.mozTransform = 'translate('+to+'px)';
}
}
function Game(noOfPlayers){
this.noOfPlayers = noOfPlayers;
this.players = new Array();
for (var i = 0; i < this.noOfPlayers ; i++){
racetrack.innerHTML = racetrack.innerHTML + track_tmpl.replace('{{ x }}', i);
this.players.push(new Players(document.getElementById('player' + i), (120 + i)));
/* issue here with dynamic added content*/
}
this.start = function(){
for (var i = 0; i < this.noOfPlayers; i++){
this.players[i].start();
}
};
}
var game = new Game(3);
game.start();
Why is that in dynamically added html only the last one moves
The issue is with creating the player(n) object inside the for loop along with the assignments to innerHTML using `+='. The modified fiddle: http://jsfiddle.net/u8Bg3/15/ works fine. Cheers for a good question!
var finalized_tracks= "" ;
for (var i = 0; i < this.noOfPlayers ; i++){
finalized_tracks += track_tmpl.replace('{{ x }}', i);
}
racetrack.innerHTML = racetrack.innerHTML + finalized_tracks;
for (var i = 0; i < this.noOfPlayers ; i++){
this.players.push(new Players(document.getElementById('player'+ i),(120+i)));
}
If you use the jquery:
var element = track_tmpl.replace('{{ x }}', i);
$(racetrack).append(element);
instead of the line where you change the innerHtml of racetrack div, all elements are moving.
However, I'm not sure, why...
theCoder has pretty much nailed the issue with your code there.
Just as an additional thought, you could manually build the necessary divs using javascript instead, it's more long winded however...
for (var i = 0; i < this.noOfPlayers ; i++){
var newTrack = document.createElement("div");
newTrack.id = "track"+i;
newTrack.className = "track";
var newPlayer = document.createElement("div");
newPlayer.id = "player"+i;
newPlayer.className = "runner";
newTrack.appendChild(newPlayer);
racetrack.appendChild(newTrack);
this.players.push(new Players(document.getElementById('player' + i), (120 + i)));
}
Trying to find the min for this stack; however, whenever I run this in JSFiddle nothing prints out... anyone explain to me why? here's the code:
function min_stack() {
var min = 0;
this.elements = [];
this.push = function(element) {
this.elements.push(element);
}
this.pop = function() {
return this.elements.pop();
}
this.min = function() {
min = this.elements[0];
if (this.elements.length > 0) {
for(int i = 0; i < this.elements.length; i++) {
if (min > this.elements[i]) {
min = this.elements[i];
}
}
}
return min;
}
}
var myStack = new min_stack();
myStack.push(5);
myStack.push(4);
myStack.push(3);
print("[" + myStack.elements + "]");
print("min:" + myStack.min());
myStack.pop();
print("[" + myStack.elements + "]");
print("min:" + myStack.min());
myStack.pop();
print("[" + myStack.elements + "]");
print("min:" + myStack.min());
There is a syntax error in your for which shows up immediately in browser console
Change:
for(int i = 0; i < this.elements.length; i++) {
TO
for(var i = 0; i < this.elements.length; i++) {
DEMO: http://jsfiddle.net/y7wET/
ALso as pointed out in comments I doubt you want to use print
int i = 0; is not valid JavaScript. JavaScript does not allow you to specify the type of a variable when declaring it; instead, use var i = 0;.
Also, because "window" is the global object, in the context of the Web page, print() is equivalent to window.print(), which prints the page to your printer.
For debugging purposes, you can pop up a message box using window.alert(); if that is too annoying, you could do something such as adding your output to a textarea element instead.