How to get this random - javascript

var mess = [];
mess.push('test1');
mess.push('test2');
mess.push('test3');
var num = Math.floor((Math.random() * mess.length));
document.writeln(mess[num]);
This code here generates a random output when refreshing the page. What I want to know how to do is get it to change automatically like dynamically on the page it will change every 5 seconds or so.
How would I go about doing this?
Any help is appreciated Thank you!

Specify a container in your HTML, instead of using document.writeln:
<span id="target">This will be filled by Javascript</span>
Now wrap your code in a function, store its result in the span, and use setTimeout to make it periodical.
var mess = [];
mess.push('test1');
mess.push('test2');
mess.push('test3');
function randomize() {
document.getElementById('target').innerHTML =
mess[Math.floor((Math.random() * mess.length))];
setTimeout(randomize, 5000);
}
randomize(); // initial call to get it going
Put the Javascript in your code after the declaration of the span, or you'll get an error stating that you Cannot set property innerHTML on NULL.

You can use recursive function.
Sorry if I missunderstood your question, but you want something like this right?
window.onload = function(){
var mess = [];
mess.push('test1');
mess.push('test2');
mess.push('test3');
(function r() {
var num = Math.floor((Math.random() * mess.length));
document.body.innerHTML = mess[num];
setTimeout(r, 5000);
})();
};

You can make use of setInterval to generate a new random index at interval of every 5 seconds and then print random value from array.
var mess = [];
mess.push('test1');
mess.push('test2');
mess.push('test3');
setInterval(
function() {
var num = Math.floor((Math.random() * mess.length))
document.write(mess[num]);
}, 5000);
Refer this fiddle
http://jsfiddle.net/3wpcp35L/

Related

Update multiple table rows in javascript

Im currently quite new to javascript and im just trying to learn some basic things. Im not so bad in other languages so i do understand concepts etc.
I have a table with 10 rows for example, One of the cells is a "CaseID" and it exists for every row. Im trying to use the Math.Random property to generate random numbers.
My problem i hit first was i was using the ID property in my HTML and obviously this is unique, next i used class. I tried to append the output with an index but this again only worked for the first cell and nothing for the rest.
HTML:
<td class="caseID"></td>
JS:
var caseID = Math.floor((Math.random() * 10000));
document.getElementsByClassName("caseID")[0].innerHTML = caseID;
This all works great for the first cell/row but every other row returns blank. Im assuming because i need to perhaps create an array/indexing but im unsure on how to do this.
Could i create a variable:
var tds = document.getelementsbyclassname("caseID");
And maybe write a foreach etc? again not sure on how to do this.
Thanks in advance!
You can try a foreach like this, which would be a lighter syntax
document.getElementsByClassName("caseID").forEach(function(element) {
var caseID = Math.floor((Math.random() * 10000));
element.innerHTML = caseID;
})
You can use a good old for loop, use a more "separate the steps" way which could help you understand more how javascript works. I will use querySelectorAll but you can do it with getElementsByClassName
var myTds = document.querySelectorAll('caseID');
// You don't want to calculate the length at each loop
for (var i = 0, length = myTds.length; i < length; i++) {
var caseID = Math.floor((Math.random() * 10000));
var element = myTds[i];
element.innerHTML = caseID;
}
Hope it helps
How about this:
var tds = document.getElementsByClassName("caseID");
if ( tds.length ) { // just a check to make sure you've found somethiung
var caseID = Math.floor((Math.random() * 10000));
for(i = 0; i < tds.length; i++) {
tds[i].innerHTML = caseID;
caseID = Math.floor((Math.random() * 10000));
}
}
You can do this by write a foreach for class element in javascript.
var cases_list = document.querySelectorAll('.caseID');
Array.prototype.forEach.call(cases_list, function(elements, index) {
// conditional here.. access elements
});
OR if you use jquery than you can do this by
$('.caseID').each(function(index, obj){
//you can use this to access the current item
});

Javascript, counting in seconds - adding a point each time

So I am working on a project of mine and I'd like some help.
I'd like javascript to be able to count in seconds, each second it'd add a preset amount of points.
var total_points = 0
var points_per_click = 1
var points_per_second = 0
function points_per_second() {
docuement.getElementById("current_points").innerHTML("Current Points: " + total_points);
//insert here?
}
I would also like the points_per_second to be able to add into the total_points var. Thanks!
docuement is spelt "document", .innerHTML is not a function call (set it like a variable) & variables and functions share the same namespace, i.e. don't set a variable points_per_second and then declare a function of the same name.
Once you have your syntax errors sorted, you were probably looking for setInterval.
var total_points = 0;
var points_per_click = 1;
var points_per_second = 2;
function update_display(){
var el = document.getElementById("current_points");
el.innerHTML = "Current Points: " + total_points;
//insert here? ... No
}
var ticker = setInterval(function(){
total_points += points_per_second;
// ... or whatever your intended logic
update_display();
}, 1000);
jsFiddle

How to get the next element of an array with Jquery onclick

Hi all i am trying to change the html of an object from an array of htmls. But i am having problem iterating properly. I managed to make it work once
EDIT
After a few complains about the clarity of my question I will rephrase it. I have a div panel called .trpanel and a button called #trigger2 (it is a next button). Then I have a series of divs with texts that contain translations. I want when I press the button (called next) to cycle through the translations one by one on the trpanel.
var ltranslation = [];
ltranslation[0] = $("#translation-en-1").html();
ltranslation[1] = $("#translation-ur-en").html();
ltranslation[2] = $("#translation-fr-en").html();
ltranslation[3] = $("#translation-it-en").html();
ltranslation[4] = $("#translation-sp-en").html();
ltranslation[5] = $("#translation-po-en").html();
ltranslation[6] = $("#translation-fr-en").html();
ltranslation[7] = $("#translation-de-en").html();
var l= ltranslation;
$("#trigger2").off('click').on('click',function(){
for (var i = 0; i <= ltranslation.length; i++){
if (i==7){i=0;}
$(".trpanel").html.ltranslation[i]; or ???//replace().ltranslation[]+i??? the code throws errors
}
});
I am quite new to Javascript and i am getting a bit confused with the types of objects and arrays and loops. I managed once to add the htmls but without replacing them ... so they all came one after the other. The i tried to change the code and it hasn't worked since. Any help will be greatly appreciated.
A lot of guessing, but seems like you are trying to do this :
var trans = $('[id^="translation-"]'),
idx = 0;
$("#trigger2").on('click',function(){
$(".trpanel").html( trans.eq(idx).html() );
idx = idx > 6 ? 0 : idx+1;
});
FIDDLE
I think you are trying to do this:
if (i == 7) {
i = 0; // I don't really know why you are doing this, but it will reset the loop
}
$(".trpanel").html(ltranslation[i]); //I'm passing ltranslation[i] to the html method. Instead of .html.ltranslation[i].
}
Also, without seeing any html, I'm not sure but I think you may want to iterate over .trpanel ?
Something like:
$(".trpanel").eq(i).html(ltranslation[i]);
Another thing (so you can make your code clearer I think). You can abstract the array population in a function, like this:
var ltranslation = [];
var languages = ["en-1", "ur-en", "fr-en", "it-en", "sp-en", "po-en", "fr-en", "de-en"];
$.each(languages, function(index) {
ltranslation[index] = $("#translation-" + this).html();
});
// Then you can use ltranslation
If you want to flip through several translations I would implement it that way:
var translations=["hej","hello", "hallo","hoy"];
var showTranslation=function(){
var current=0;
var len=translations.length;
return function(){
var direction=1;
if (current>=len) current=0;
$("#text").text(translations[current]);
current+=direction;
}
}();
$("#butt").on("click", showTranslation);
Fiddle: http://jsfiddle.net/Xr9fz/
Further: You should give your translations a class, so you could easily grab all of them with a single line:
$(".translation).each(function(index,value){ ltranslation.push(value); })
From the question : I managed once to add the htmls but without replacing them -
I think you want to add all of these items into $(".trpanel"). First, dont take the HTML of each element, clone the element itself :
//method ripped from Nico's answer.
var ltranslation = [];
var languages = ["en-1", "ur-en", "fr-en", "it-en", "sp-en", "po-en", "fr-en", "de-en"];
$.each(languages, function(index) {
ltranslation[index] = $("#translation-" + this).clone();
});
Then you could append everything into the container, so add the htmls but without replacing them. append takes in an array without replacing the previous html.
$("#trigger2").off('click').on('click',function() {
$(".trpanel").append(ltranslation);
});
I don't know what exactly you're tring to do, but I've put comments in your code to help you better understand what your code is doing. The net effect of your code is this (which I doubt you want) :
$("#trigger2").off('click').on('click',function(){
$(".trpanel").html(ltranslation[7]);
});
This is your code with some comments and minor changes
var ltranslation = [];
ltranslation[0] = $("#translation-en-1").html();
ltranslation[1] = $("#translation-ur-en").html();
ltranslation[2] = $("#translation-fr-en").html();
ltranslation[3] = $("#translation-it-en").html();
ltranslation[4] = $("#translation-sp-en").html();
ltranslation[5] = $("#translation-po-en").html();
ltranslation[6] = $("#translation-fr-en").html();
ltranslation[7] = $("#translation-de-en").html();
var l= ltranslation;
$("#trigger2").off('click').on('click',function(){
for (var i = 0; i < ltranslation.length; i++){
//if (i==7){i=0;} <-- This will cause an infinite loop won't it? are you trying to reset i? i will reset next time loop is called,
$(".trpanel").html(ltranslation[i]); //<-- this will overwrite elements with class .trpanel ltranslation.length times...
///you'll see only the value of translation[7] in the end
}
});
EDIT
To do what you want to do based on your comments, try this:
var ltranslation = [];
ltranslation[0] = $("#translation-en-1").html();
ltranslation[1] = $("#translation-ur-en").html();
ltranslation[2] = $("#translation-fr-en").html();
ltranslation[3] = $("#translation-it-en").html();
ltranslation[4] = $("#translation-sp-en").html();
ltranslation[5] = $("#translation-po-en").html();
ltranslation[6] = $("#translation-fr-en").html();
ltranslation[7] = $("#translation-de-en").html();
var counter = 0;//a global counter variable
$("#trigger2").click(function(){ //eeverytime button is clicked do this
$(".trpanel").html(ltranslation[counter]); //set the html to an element of array
counter++; //increment counter
if(counter==ltranslation.length) //reset the counter if its bigger than array len
counter=0;
});

Looping two variables and testing every 1000ms

I have two variables:
var frame = $('#avacweb_chat iframe');
var time = $('.date-and-time' , frame.contents()).last().text();
var newTime = setInterval(function() {
var newT = $('.date-and-time' , frame.contents()).last().text();
},500);
As you can see one variable is in a setInterval and the other is not. So technically when I test these in a conditional it has to be inside the interval. Does anyone know how I can get these so that it will update the first variable if the second variable changes and then loop again? EX:
Var Time = [12:30:39 23/05/13]
Var newT = [12:31:39 23/05/13]
So now
Var Time = [12:31:39 23/05/13]
So then we would now need to test the var NewT again. Hope this explained it a little better. I am going to keep trying different things though if you have a suggestion please post it. Thanks guys
I could misunderstood your problem, but use:
var frame = $('#avacweb_chat iframe');
var time = $('.date-and-time' , frame.contents()).last().text();
var newTime = setInterval(function() {
var newT = $('.date-and-time' , frame.contents()).last().text();
if(newT != time)//seems like always true but im just speculating
time = newT;
},500);

Javascript using different configurations for different outputs

Hi being a complete and utter idiot at the moment, where I have staring at this stuff for hours and now have no clue what I am doing.
Basically in one which I will name here as product.js I have Global Variables fixed
var AREA_MAX_MAXX = 1000;
var AREA_MAX_MINX = 60;
these are being then being used within another js which I will call library.js with the following:
this.area_max_maxx = AREA_MAX_MAXX;
this.area_max_miny = AREA_MAX_MINX;
this.calcPos = function() {
var areaMaxWidth = this.area_max_maxx - this.area_max_minx;
What I want to do is remove the Global Variables and instead have it set up with arrays, so that whatever the array is the values will be set forarea_max_maxx
Can anyone help me out there??? Am I making sense?
You mean like this?
this.minAndMax = [60, 1000];
this.calcPos = function() {
var areaMaxWidth = this.minAndMax[1] - this.minAndMax[0];
}
I would recommend instead using an object:
this.areaParameters = {min: 60, max: 1000}
this.calcPos = function() {
var areaMaxWidth = this.areaParameters.max - this.areaParameters.min;
}
Later, you can just say this.areaParameters.max = 3000 and next time calcPos gets called it will use the new value.
This is not possible. You are passing a value not a reference here:
this.area_max_maxx = AREA_MAX_MAXX;

Categories