I have a group of divs called "oponente", and if the user do not click on one of them in five seconds the script will choose one randomly. What I dont know how to do is to keep in LocalStorage which div the script had choose. Here is my script, I dont know what to write on 'key name' and so on.
$(document).ready(function () {
$(".oponente").addClass("gray");
var elements = $(".oponente");
var elementCount = elements.size();
var elementsToShow = 1;
var alreadyChoosen = ",";
var i = 0;
while (i < elementsToShow) {
var rand = Math.floor(Math.random() * elementCount);
if (alreadyChoosen.indexOf("," + rand + ",") < 0) {
alreadyChoosen += rand + ",";
setTimeout(function () {
elements.eq(rand).window.localStorage.setItem('key name', 'key name');
}, 5000);
++i;
}
}
});
You can store index of selected one. Then you can get child from the parent with that index number clearly.
Let me simulate
$(document).ready(function () {
$(".oponente").addClass("gray");
var elements = $(".oponente");
var elementCount = elements.size();
var elementsToShow = 1;
var alreadyChoosen = ",";
var i = 0;
while (i < elementsToShow) {
var rand = Math.floor(Math.random() * elementCount);
if (alreadyChoosen.indexOf("," + rand + ",") < 0) {
alreadyChoosen += rand + ",";
setTimeout(function () {
localStorage.setItem('indexOfSelected', selectedDiv.index());
}, 5000);
++i;
}
}
});
Then you can get the selected div with
var indexOfSelected = localStorage.getItem('indexOfSelected');
myDiv = parentDiv.children(":eq("+indexOfSelected+")")
All you need to init a selectedDiv then a parentDiv which is parent of the selectedDiv.
Related
what I have in here is a simple slider with two images. Is there a way to change the var file of imageSwap() when the counter hits 12?
var number = Math.floor(Math.random() * 2) + 1;
var timer1 = 0;
var timer2 = 0;
function imageSwap(id) {
var img = document.getElementById("app" + id);
img.src = "red.png";
img.classList.add("selected");
var count = document.querySelectorAll(".selected").length;
console.log(count);
if (count == 12) {
// Change var file image of function Change()
}
}
function hide() {
$("#slider").fadeOut(500);
}
function change() {
number++;
if (number > 2) number = 1;
var file = '<img src="tree' + number + '.png" />';
document.getElementById("slider").innerHTML = file;
$("#slider").fadeIn(500);
timer1 = setTimeout("change()", 5000);
timer2 = setTimeout("hide()", 4500);
}
Thanks in advance!
I have created a button using JavaScript, and I have a list that is supposed to get a random number when I "roll the dice"
I need to list of numbers to say "You rolled a 1" for example. How do I do that? And also I only need it to show the last 10 numbers.
var rollNumber = 0;
var values = [];
function dieRolled() {
rollNumber += 1;
var numRolled = Math.ceil(Math.random() * 6);
values.push(numRolled);
document.getElementById("results").innerHTML = "";
for (var x = values.length-1 ; x>=0; x--) {
var newRoll = document.createElement("li");
newRoll.innerHTML = values [x] +"You rolled a";
document.getElementById("results").appendChild(newRoll);
if (x == 11)break;
}
}
How about this?
var output = document.getElementById("Output");
var values = [];
function roll()
{
values.push(Math.ceil(Math.random() * 6));
// If the history is too big, drop the oldest...
if (values.length > 10)
{
values.shift();
}
// Rewriting the history log
var text = "";
for (var i in values)
{
text += "You rolled a " + values[i] + "\n";
}
output.innerHTML = text;
}
// Rolling multiple times
setInterval(function(){ roll(); }, 1000);
<pre id="Output"></pre>
Try this:
var list = document.getElementById('demo');
var count = 0;
function changeText2() {
count++;
if(count <= 10)
{
var numRolled = Math.ceil(Math.random() * 6);
var entry = document.createElement('li');
entry.appendChild(document.createTextNode("You rolled:"+numRolled));
list.appendChild(entry);
}
}
<input type='button' onclick='changeText2()' value='Submit' />
<p>Dices you rolled</p>
<ol id="demo"></ol>
I am building a very simple memory game for a small project. The logic is as follows:
click on the input field to choose with how many pairs would you like to play
create divs with classes card1, card2 etc.
clone divs and randomize their place in the array
Here is my script (fork in JSFiddle):
$(".button").click(function () {
// get the value from the input
var numCards = parseInt($('input').val());
for (var i = 1; i <= numCards; i++) {
// create the cards
$(".container").append("<div class='card" + i + " cards'></div>") &&
$(".card" + i).clone().appendTo(".container");
}
// randomize cards in stack
var cards = $(".cards");
for (var i = 0; i < cards.length; i++) {
var target = Math.floor(Math.random() * cards.length - 1) + 1;
var target2 = Math.floor(Math.random() * cards.length - 1) + 1;
var target3 = Math.floor(Math.random() * cards.length - 1) + 1;
cards.eq(target).before(cards.eq(target2)).before(cards.eq(target3));
}
});
what I need now is to adjust the 3rd step, meaning to dynamically create the target vars, and the last line of the code
cards.eq(target).before(cards.eq(target2)).before(cards.eq(target3));
So please make me a suggestion - how would you do it? And bare in mind this is a project for beginners. Thank you!
$(".button").click(function () {
// get the value from the input
var numCards = parseInt($('input').val());
for (var i = 1; i <= numCards; i++) {
// create the cards
$(".container").append("<div class='card" + i + " cards'></div>") &&
$(".card" + i).clone().appendTo(".container");
}
var parent = $(".container");
var divs = parent.children();
while (divs.length) {
parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]);
}
});
see jsfidle: http://jsfiddle.net/007y4rju/8/
source: http://jsfiddle.net/C6LPY/2/
Here is the version of the code in jsfiddle - http://jsfiddle.net/007y4rju/6/
Please, check if the behavior is consistent with the original code.
$(document).ready(function () {
$(".button").click(function () {
// get the value from the input
var numCards = parseInt($('input').val());
for (var i = 1; i <= numCards; i++) {
// create the cards
$(".container").append("<div class='card" + i + " cards'></div>") &&
$(".card" + i).clone().appendTo(".container");
}
// randomize cards in stack
var cards = $(".cards");
var startTarget = Math.floor(Math.random() * cards.length - 1) + 1;
var collection = cards.eq(startTarget);
var nextTarget;
var i;
for (i = 0; i < cards.length; i++) {
nextTarget = Math.floor(Math.random() * cards.length - 1) + 1;
collection.before(cards.eq(nextTarget));
}
});
});
You can randomize index in a class name (card%i%) when cloning divs. Then you don't need to shuffle cloned divs; you can append them as is.
$(".button").click(function () {
// get the value from the input
var numCards = parseInt($('input').val());
for (var i = 1; i <= numCards; i++) {
// create the cards
$(".container").append("<div class='card" + i + " cards'></div>");
}
var aIndices = [];
for (var i = 1; i <= numCards; i++) {
var ix;
do ix = Math.round(Math.random() * (numCards - 1)) + 1;
while (aIndices.indexOf(ix) >= 0);
aIndices.push(ix);
// clone
$(".card" + ix).clone().appendTo(".container");
}
});
The below code selects random images,I want it to select linearly and display the next 8 images in next refresh.
$.fn.preload = function() {
this.each(function(){
$('<img/>')[0].src = this;
});
}
function preloadImg(totalClients)
{
for(var i = 1; i <= totalClients; i++)
{
$('<img src="images/clients/' + i + '.jpg"/>');
}
}
function getRandoms(numPicks, low, high) {
var len = high - low + 1;
var nums = new Array(len);
var selections = [], i;
// initialize the array
for (i = 0; i < len; i++) {
nums[i] = i + low;
}
// randomly pick one from the array
for (var i = 0; i < numPicks; i++) {
var index = Math.floor(Math.random() * nums.length);
selections.push(nums[index]);
nums.splice(index, 1);
}
return(selections);
}
function randomClients(totalClients)
{
rarr = getRandoms(8,1,totalClients);
$(".pretty-box").each(function(index)
{
$(this).fadeOut(function(){
src = "images/clients/" + rarr[index] + ".jpg" ;
$(this).attr('src',src);
$(this).fadeIn();
});
});
}
We are able to pick the first 8 images from our array but not the next 8 images.
Can someone help us with this?
I followed a tutorial/modified the code to get a javascript tag cloud working in IBM Cognos (BI software). The tag cloud works fine in FireFox but in Internet Explorer I get the error:
"Message: '1' is null or not an object"
The line of code where this is present is 225 which is:
var B = b[1].toLowerCase();
I have tried many different solutions that I have seen but have been unable to get this working correctly, the rest of the code is as follows:
<script>
// JavaScript Document
// ====================================
// params that might need changin.
// DON'T forget to include a drill url in the href section below (see ###) if you want this report to be drillable
var delimit = "|";
var subdelimit = "[]"; // change this as needed (ex: Smith, Michael[]$500,000.00|)
var labelColumnNumber = 0; // first column is 0
var valueColumnNumber = 1;
var columnCount = 2; // how many columns are there in the list?
// ====================================
/*
function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + '$' + num + '.' + cents);
}
*/
function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
return ( num );
}
function filterNum(str) {
re = /\$|,|#|#|~|`|\%|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\!|\$|/g;
// remove special characters like "$" and "," etc...
return str.replace(re, "");
}
table = document.getElementById("dg");
if ( table.style.visibility != 'hidden'){ //only for visible
/*alert('Visible');*/
tags = document.getElementById("dg").getElementsByTagName("SPAN");
txt = "";
var newText = "a";
for (var i=columnCount; i<tags.length; i++) {
/*
valu = filterNum(tags[i+valueColumnNumber].innerHTML);
txt += valu;
txt += subdelimit+tags[i+labelColumnNumber].innerHTML+delimit;
i = i+columnCount;
*/
if(i%2!=0){
var newValue = filterNum(tags[i].innerHTML);
}else var newName =tags[i].innerHTML;
if((i>2) & (i%2!=0)){
newText = newText+newValue+subdelimit+newName+delimit;
if(typeof newText != 'undefined'){
txt = newText;
txt = txt.substr(9);
/* alert(txt);*/
}
}
}
}/*else alert ('Hidden');*/
function getFontSize(min,max,val) {
return Math.round((150.0*(1.0+(1.5*val-max/2)/max)));
}
function generateCloud(txt) {
//var txt = "48.1[]Google|28.1[]Yahoo!|10.5[]Live/MSN|4.9[]Ask|5[]AOL";
var logarithmic = false;
var lines = txt.split(delimit);
var min = 10000000000;
var max = 0;
for(var i=0;i<lines.length;i++) {
var line = lines[i];
var data = line.split(subdelimit);
if(data.length != 2) {
lines.splice(i,1);
continue;
}
data[0] = parseFloat(data[0]);
lines[i] = data;
if(data[0] > max)
max = data[0];
if(data[0] < min)
min = data[0];
}lines.sort(function (a,b) {
var A = a[1].toLowerCase();
var B = b[1].toLowerCase();
return A>B ? 1 : (A<B ? -1 : 0);
});
var html = "<style type='text/css'>#jscloud a:hover { text-decoration: underline; }</style> <div id='jscloud'>";
if(logarithmic) {
max = Math.log(max);
min = Math.log(min);
}
for(var i=0;i<lines.length;i++) {
var val = lines[i][0];
if(logarithmic) val = Math.log(val);
var fsize = getFontSize(min,max,val);
dollar = formatCurrency(lines[i][0]);
html += " <a href='###Some drillthrough url which includes the param "+lines[i][1]+"' style='font-size:"+fsize+"%;' title='"+dollar+"'>"+lines[i][1]+"</a> ";
}
html += "</div>";
var cloud = document.getElementById("cloud");
cloud.innerHTML = html;
var cloudhtml = document.getElementById("cloudhtml");
cloudhtml.value = html;
}
function setClass(layer,cls) {
layer.setAttribute("class",cls);
layer.setAttribute("className",cls);
}
function show(display) {
var cloud = document.getElementById("cloud");
var cloudhtml = document.getElementById("cloudhtml");if(display == "cloud") {
setClass(cloud,"visible");
setClass(cloudhtml,"hidden");
}
else if(display == "html") {
setClass(cloud,"hidden");
setClass(cloudhtml,"visible");
}
}
generateCloud(txt);
</script>
Any help or explanations is much appreciated
Sorry, I'm not seeing where a[] and b[] are defined, is this done elsewhere? Firefox and IE may be responding differently to the problem of an undefined array.