Basically. I am creating a preloader page for my site. I want the icon in the middle of the page to change everytime the visitor comes to my page. I need to select a variable or a string within the array.
My code:
$(document).ready(function() {
//randomly pick a number an pick an icon to show on main page
//Math.floor(Math.random() * 6) + 1 [from SOF]
var min = 1,
max = 8;
var number = Math.floor(Math.random() * (max - min + 1) + min);
var icons = ['preload/img/audio.svg', 'preload/img/bars.svg', 'preload/img/grid.svg', 'preload/img/oval.svg', 'preload/img/puff.svg', 'preload/img/rings.svg', 'preload/img/tail-spin.svg', 'preload/img/three-dots.svg'];
alert(number);
});
I have tried alert(icons.get(numbers)); but never worked. I have been searching for a while and cannot figure it out.
You need to retrieve the icon using the index.
Also, for the random, it returns a float between 0 and 1, so as an array is 0 based, and you have 8 items, you need to:-
$(document).ready(function() {
var number = Math.round(Math.random() * 7);
var icons = ['preload/img/audio.svg', 'preload/img/bars.svg', 'preload/img/grid.svg', 'preload/img/oval.svg', 'preload/img/puff.svg', 'preload/img/rings.svg', 'preload/img/tail-spin.svg', 'preload/img/three-dots.svg'];
alert(icons[number]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var icons = ['preload/img/audio.svg', 'preload/img/bars.svg', 'preload/img/grid.svg', 'preload/img/oval.svg', 'preload/img/puff.svg', 'preload/img/rings.svg', 'preload/img/tail-spin.svg', 'preload/img/three-dots.svg'];
var imageNum = Math.floor(Math.random()*icons.length);
document.getElementById("myIcon").src = icons[imageNum];
Where "myIcon" is the id of the image you want to change.
Related
I'm looking for a solution to show only 1 div with rate 1/100. Now I'm using this javascript:
var random = Math.floor(Math.random() * $('.item').length);
$('.item').hide().eq(random).show();
It solves my problem if I create 100 div's with .item class but it makes a huge mess in my code.
I asume you want to show a div randomly when you refresh the page.
Javascrip (jquery):
$(document).ready(function(e) {
var randomNum = Math.floor(Math.random() * 100) + 1 ;
$(".item_" + randomNum).show();
});
HTML:
<div class="item_1" style="display:none;">This div show randomly</div>
https://jsfiddle.net/12f9hpny/
When random number is 1 this div will show.
Hope this will help.
Why don't you just do:
// Random number between 1 and 100
var random = (Math.random() * 100) + 1;
// Gets the element to show
var element = $('.item');
// Show the element only if random == 1
if(random == 1) element.show();
I'm trying to get a random integer which is between two given values and has not been extracted yet with javascript.
To do that, I'm using the following code:
var extracted = [];
function rand(){
var from = document.getElementById('from').value;
var to = document.getElementById('to').value;
var number = Math.floor(from) + Math.floor(Math.random() * to);
var alreadyextracted = (extracted.indexOf(number) > -1);
if(alreadyextracted){
var maximum = Math.floor(to) - Math.floor(from);
var count = extracted.length;
if(count > maximum){document.getElementById('result').innerHTML='All numbers have been extracted.';}
else{rand();}
}
else{document.getElementById('result').innerHTML=number;
extracted.push(number);
if(extracted[0] == number){var content = number;}
else{var before = document.getElementById('got').innerHTML;
var content = number + ', ' + before;}
document.getElementById('got').innerHTML= content;
}
}
From: <input id="from" value="1">
To: <input id="to" value="10">
<input type="button" value="Extract" onclick="rand()">
<div id="result"></div>
<div id="desc">Already extracted numbers:</div>
<div id="got"></div>
It works fine if i put a "from" value which is lower than 10, but, if it is greater, it gets a completely random integer and randomly says that all numbers have been extracted even if it's not true.
I don't see anything in the firefox console.
What could be the problem?
You're doing it all wrong.
Fill an array with all of your range of numbers from smallest to largest.
Use a Fisher/Yates/Knuth shuffle to mix the array.
Draw out as many numbers as you need.
(No code included on purpose because I didn't fix your problem)
Spender is not wrong but the problem lies in the way you generate you random numbers:
var number = Math.floor(from) + Math.floor(Math.random() * to);
That's not the proper way to generate a number between min and max. This should be:
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Use the method proposed by spender and then pick an element in the remaining set using this function (In this case min will be 0 and max the number of remaining elements-1)
If I have an array of buttons, how can I tell which button was clicked?
example below
var i=0
CreateButton = new function () {
savebutton[i]=NewButton()
i++
}
every time a user runs the function a new button is generated.
the first button is savebutton[0] the second is savebutton[1] and so on potentially infinity times.
when later the user presses the button I want the screen to alert it's index number (or 'i').
is there any way to make this work in arrays?
this : savebutton[i].click(alert(this))
and this: savebutton[i].onClick(alert(this))
do not work
the code is entirely written in RephaelJs and contains absolutely no DOM elements.
I use RaphaelJS and my HTML document contains no DOM elements. everything is scripted.
the entire function that generates the buttons:
var insertframe = function () {
ww = WindowWidth
mw = mywindoww
zx = zone.getBBox().x
zy = zone.getBBox().y
zw = zone.getBBox().width
zh = zone.getBBox().height
sh = screen.getBBox().height
sw = screen.getBBox().width
py = picy
px = picx
srw = screenratiow
srh = screenratioh
savebutton[i] = paper.image(imageurl)
savebutton[i].attr(
{
'width': px * (framewidth * miniframesize) / zw,
'height': py * (frameheight * miniframesize) / zh,
'x': ((srw*520) + (i * 120) * srw) - zx * (frameheight * miniframesize) / zh,
'y': srh*600 - zy * (framewidth * miniframesize) / zw,
'clip-rect': (srw*520) + (i * 120) * srw + "," + srh * 600 + "," + framewidth * miniframesize + ',' + frameheight * miniframesize
})
savebutton[i].click(alert(this))
i++
}
When you create the button, you can assign its index from the array as an attribute of the button and then when it's clicked on, you can examine that attribute of the clicked on button to see where it is positioned in the array.
If you don't want to do that, you can also search the array and find where the current button is in the array.
You can use a 2d array with each element having an ID and an identifier. Can't say too much more without seeing your code.
I think JQuery might help you achieve that way easier. Check out this:
http://api.jquery.com/index/
Hope this helps!
I'm creating a slider with 6 slides, and I want to randomly move between them, making sure that neither of the previous two slides are shown as the next slide. The functionality doesn't really matter, since what I'm really doing is generating random numbers and keeping track of the previous two. The first slide is always numbered 1, so for the first two iterations that'll be one of the previous numbers that can't be used.
Here's what I have so far, and it works fine for generating the random numbers in the range, but 'caching' the last two values doesn't work reliably:
var rand = Math.floor(Math.random() * 6) + 1;
var prev1 = 1;
var prev2;
function randomSlide() {
// 5 second interval between slides
// Don't show either of previous two slides next
random = setInterval(function() {
prev2 = prev1;
prev1 = rand;
do {
rand = Math.floor(Math.random() * 6) + 1;
} while (rand == prev1 || rand == prev2);
prev1 = rand;
$('#slider').anythingSlider(rand);
//console.log(prev1,prev2);
}, 5000);
}
function firstSlide() {
firstTime = setTimeout(function() {
randomSlide();
}, 5000);
}
firstSlide();
randomSlide();
It's quite simple I think but my brain's getting frazzled trying to parse the values of the two 'cache' variables at the first, and then each subsequent, iteration.
I'm executing a single iteration at the beginning because if randomSlide() executes on load then the first (welcome) slide doesn't get a chance to display.
When you do the prev1 = rand the second time after you've changed the value of rand, you're assigning the new slide's number to it. The next time you enter the loop you do prev2 = prev1, and since prev1 == rand it means that now all three variables prev1, prev2 and rand are the same. Just remove the second prev1 = rand.
Another issue is that you set the interval twice: first you call firstSlide() which executes randomSlide() after a 5 second delay (which sets one interval), then right after you call randomSlide() again which sets another interval.
Here's another (simpler?) approach to getting the result:
<script>
// Return a random number from 1 to 6, exclude
// the last two numbers.
var getRandom = (function() {
var a = [1,2,3,4,5,6];
return function() {
var i = (Math.random() * 4 ) | 0;
a[5] = a.splice(i,1);
return a[5];
}
}());
function writeRandom() {
document.getElementById('d0').innerHTML += getRandom() + '<br>';
}
setInterval(writeRandom, 100)
</script>
<div id="d0"></div>
Not exactly random for the first 2 iterations, but you can fix that by randomising the array when it's initialised. But likely it doesn't matter for a slide show.
It's less code, but the splice part makes it slower in the browsers I tested. My version of the OP is:
var getRandom2 = (function() {
var r0 = r1 = r2 = 1;
return function() {
r0 = r1;
r1 = r2;
do {
r2 = Math.floor(Math.random() * 6) + 1;
} while (r2 == r0 || r2 == r1);
return r1;
}
}());
How would I select a random value (0 to 30) that is not in this array?
var list = new Array(1,3,4,7,8,9);
Build the complementary array and pick random values from it.
var list2 = new Array();
for(var i=0; i<30; i++)
if(!list.contains(i))
list2.push(i);
Then:
var rand = list2[Math.floor(Math.random() * list2.length)];
function RandomValueNotInArray(array)
{
var e;
do
{
e = Math.random() * 31; // n + 1
} while (array.contains(e))
return e;
}
Assuming your list is reasonable small in size, create a list of numbers that are not in the array and then select a number from that array at random.
You need a while loop that tests if rand is in your restricted array and, if so, re-generate a new random number:
var rand;
do {
rand = Math.floor(Math.random() * 31); // re-randomize, 0 to 30 inclusive
} while ($.inArray(rand, restricted) > -1);
return rand;
http://jsfiddle.net/mblase75/dAN8R/
Don't want jQuery? You can replace $.inArray(rand, restricted) with restricted.indexOf(rand) if you use this polyfill for old browsers.
A little recursive function:
getNum() {
let randomNum = Math.floor(Math.random() * (30 - 1)) + 1
if (list.includes(randomNum)) {
return getNum()
}
return randomNum
}
Might be a little faster, since it first tries to return a random number, and then checks if it's in the array.
I would probably make an array or linked list from which I would subtract the unwanted items. That way I could keep removing items and just randomly select items from position 0 to the array's length - 1 without having to select the same thing twice.
Another way of doing it is to randomize a number between 0 and 30 and to keep doing it while it is found in the array. The only problems with that is knowing when the array is full (to get rid of infinite loops) and that it is a whole lot more processor intensive.
you can use filter .
var filteredArray = list.filter(function(e){
return e!= Math.floor(Math.random() * (31));
});
PHP in 2 lines:
$result = array_diff(range(1,30), array(1,3,4,7,8,9));
echo $result[array_rand($result)];