need a bit of help with a random image array. I need to create 5 images that come up at random when the Start button is clicked (1 at a time) and then have 5 buttons. The 5 buttons that stay there correspond to the random images. First button = image[1] (from array) etc.
img0 stays on the screen and is swapped out for the random images from the array.
I can't seen to get the random image to display. It's probably something simple but I'm banging my head against a wall with it.
Any help you guys can give would be great.
HTML
<div style="background-color:grey; position: absolute; left:50px; top:150px">
<img src="img0.jpg" id="osBus" alt="0" />
</div>
CODE
<input id="b2" type="button" onclick="btn2_onClick()" value="2" style="position:absolute; left:125px; top:375px"
disabled class="btns" />
<input id="b3" type="button" onclick="btn3_onClick()" value="3" style="position:absolute; left:225px; top:375px"
disabled class="btns" />
<input id="b4" type="button" onclick="btn4_onClick()" value="4" style="position:absolute; left:325px; top:375px"
disabled class="btns" />
<input id="b5" type="button" onclick="btn5_onClick()" value="5" style="position:absolute; left:425px; top:375px"
disabled class="btns" />
<br />
<script language="javascript">
var Imgs = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jog"];
var Num
function btnStart_onClick() {
Num = 1 + parseInt(Math.random() * 5);
document.getElementById("Imgs") == Imgs[Num];
}
Any help you guys can offer with this would be greatly appreciated.
Thanks
Imgs array does not have an element at index 5. Use
Math.floor(Math.random() * Imgs.length)
Also no element has id "Imgs"; do you mean "osBus"? You can change the displayed image by setting the src attribute of an <img> element.
var Imgs = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg"];
var Num = 0;
function btnStart_onClick() {
Num = Math.floor(Math.random() * Imgs.length);
document.getElementById("osBus").src = Imgs[Num];
}
You have to update the src property.
And a few things:
Why are you doing document.getElementById("Imgs") when there is no element where id="Imgs"?
Where is btnStart_onClick called from?
Use = for assignment
You only need to multiply by 4, as Math.random() returns 0 -> 1
function btnStart_onClick() {
var imgNum = (1 + (Math.round(Math.random() * 4)));
document.getElementById("osBus").src = imgNum + '.jpg';
}
var Imgs = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jog"];
var Num;
function randomNumber(min, max) {
return Math.floor(Math.random() * ((max - min) + 1) + min);
}
function btnStart_onClick() {
Num = randomNumber(0, 4);
document.getElementById("osBus").src = Imgs[Num];
}
Related
I have an HTML element input of type range:
<body onload="rotar()">
<img src="#" id="locator" />
<input type="range" name="points" id="loop" min="1" max="20" data-show-value="true">
</body>
It goes basically like this: This page shows images that change dynamically and I want the slider with ID loop to change its value, just like the images so it moves according to them.
function rotar(){
var slider = document.getElementById("loop");
var locator = document.getElementById('locator'),
dir = 'static/visor/img/',
delayInSeconds = 3,
num = 1,
len = 20;
setInterval(function(){
locator.src = dir + num+'.png';
if (num === len){
num = 1;
}
else{
num++;
}
slider.value = num;
}, delayInSeconds * 50);}
I don't have any image dir so i just did it with an simple input. please check this http://jsfiddle.net/maxofpower/tAs6V/275/
<body onload="rotar()">
<form ><div>
<input id="loop" onchange="amount.value=rangeInput.value" oninput="amount.value=rangeInput.value" type="range" min="0" max="200" name="rangeInput" />
<input id="box" type="text" value="0" name="amount" for="rangeInput" oninput="rangeInput.value=amount.value" />
</div></form>
</body>
<script>
function rotar() {
var slider = document.getElementById("loop");
var num = 1;
setInterval(function(){
slider.value = num++;
}, 500);
};
</script>
Your issue is with the delay passed to the setInterval method, as the delay argument is in milliseconds, to get 2.8 seconds you'd have to multiply the delayInSeconds variable by 1000.
You had some mistakes in your code, you refreferenced the img#locator element with the variable name rotator the you used the variable name locator, which will cause an Undefined variable error. Im my answer I changed the variable's name from rotator to locator, also I made the delay to 2.8 seconds.
Here's a demo:
function rotar() {
var slider = document.getElementById("loop"),
locator = document.getElementById('locator'),
dir = 'static/visor/img/',
delayInSeconds = 2.8,
num = 1,
len = 20;
setInterval(function() {
locator.src = dir + num + '.png';
num = (num === len) ? 1:num + 1;
slider.value = num;
}, delayInSeconds * 1000);
}
<body onload="rotar()">
<img src="#" id="locator" />
<input type="range" name="points" id="loop" min="1" max="20" data-show-value="true">
</body>
I am working on a personal coin flip project in HTML and Javascript. Is there a way to make the an image change based on the result of the "flip". For instance if it lands on heads it shows an image of a quarter on its heads side and same for tails?
Javascript Code:
document.getElementById('click').onclick = click;
var heads = 0;
var tails = 0;
function click() {
x = (Math.floor(Math.random() * 2) == 0);
if(x){
flip("heads");
}else{
flip("tails");
}
};
function flip(coin) {
document.getElementById("result").innerHTML = coin;
};
HTML Code:
<button id="click" type="button">CLICK ME</button>
<p>You got: <span id="result"></span></p>
You have the working code you just need this...
var coins = {
heads: 'http://lorempixel.com/400/200/sports/heads is sports',
tails: 'http://lorempixel.com/400/200/animals/tails is animals',
}
document.getElementById("result").setAttribute('src', coins[coin])
document.getElementById('click').onclick = click;
var heads = 0;
var tails = 0;
var coins = {
heads: 'http://lorempixel.com/400/200/sports/heads is sports',
tails: 'http://lorempixel.com/400/200/animals/tails is animals',
}
function click() {
var result = Math.floor(Math.random() * 2) == 0 ? 'heads' : 'tails';
flip(result)
};
function flip(coin) {
document.getElementById("result").setAttribute('src', coins[coin])
};
<button id="click" type="button">CLICK ME</button>
<p>You got: <img id="result" /></p>
Simply change the .src on an <img />:
(The link can be anything you want, including a relative path, for example: "../../img/")
document.getElementById('click').onclick = click;
var heads = 0;
var tails = 0;
function click() {
x = (Math.floor(Math.random() * 2) == 0);
if(x){
flip("head");
}else{
flip("tail");
}
};
function flip(coin) {
var link = "http://www.marshu.com/articles/images-website/articles/presidents-on-coins/half-dollar-coin-";
document.getElementById("result").src = link+coin+".jpg";
};
img {width:100px;}
<button id="click" type="button">CLICK ME</button>
<p>You got: <img id="result" src="" /></p>
I have a function called start that is triggered when you push the start button. The start function calls another function called getRandomImage. I want getRandomImage to repeat every 5 seconds, but I just can't get the setInterval method to work for me. I've tried putting the interval on the start function, but that just causes it to fire off once, and doesn't repeat. I've tried putting the interval on the getRandomImages function, but then it doesn't do anything. Essentially I am trying to make a color blindness test that flashes a random image every 5 seconds until 30 images have passed or the user clicks a button. I've been banging my head against this for over 8 hours, and am really questioning my choice in programming languages right now, lol.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"
<title></title>
<link rel="stylesheet" href="ColorPerceptionTest.css">
</head>
<body>
<section>
<img src="Default.png" id="defaultimage">
<form>
<input type="button" id="Button1" value="" onClick="">
<input type="button" id="Button2" value="" onClick="">
<input type="button" id="Button3" value="" onClick="">
<br>
<input type="button" id="Start" value="Start" onClick="start()">
<input type="button" id="Help" value="Help" onClick="help()">
<br>
<p id="help"> </p>
</form>
</section>
<script>
var $ = function(id) {
return document.getElementById(id);
}
$("Button1").style.display = "none";
$("Button2").style.display = "none";
$("Button3").style.display = "none";
var imagesArray = ["3.gif", "05.gif", "5.gif", "6.gif", "7.gif",
"8.gif", "12.gif", "15.gif", "16.gif", "26.gif",
"29.gif", "42.gif", "45.gif", "73.gif",
"74.gif"];
var runTimer = setInterval(start, 5000);
function getRandomImage(imgAr, path) {
path = path || 'images/';
var num = Math.floor( Math.random() * imgAr.length );
var img = imgAr[ num ];
var imgStr = '<img src="' + path + img + '" alt = "">';
$("defaultimage").src = path + img;
$("Button1").style.display = "initial";
$("Button2").style.display = "initial";
$("Button3").style.display = "initial";
if(parseInt(img) < 8){
$("Button1").value = parseInt(img);
$("Button2").value = parseInt(img) - 2;
$("Button3").value = parseInt(img) + 1;
}else if(parseInt(img) > 7 && parseInt(img) < 29){
$("Button1").value = parseInt(img) - 2;
$("Button2").value = parseInt(img);
$("Button3").value = parseInt(img) + 1;
}else{
$("Button1").value = parseInt(img) - 5;
$("Button2").value = parseInt(img) - 9;
$("Button3").value = parseInt(img);
}
}
var start = function(){
$("help").innerHTML = "";
getRandomImage(imagesArray);
$("Start").style.display = "none";
$("Help").style.display = "none";
}
var help = function (){
$("help").innerHTML = "This is a test designed to help you determine" +
" if you have a problem with seeing colors. When you press start, a series of " +
"random images will be displayed. You have 5 seconds to read the number and " +
"select the correct button.";
}
</script>
</body>
Try moving the setInterval call to a point where start is defined...
Your code works fine in this fiddle.
var start = function(){
$("help").innerHTML = "";
getRandomImage(imagesArray);
$("Start").style.display = "none";
$("Help").style.display = "none";
}
var runTimer = setInterval(start, 5000);
Update: To make it more clear, had OP written function start() the posted code would have been properly hoisted. But, as he used a function expression, start is undefined when setInterval is called.
Another update: Here's a forked fiddle to correct the timer based on the button and the comments below.
These are the instructions:
"Have an image and two buttons, PREV and NEXT. Have 10 images in an array. When you click on NEXT, the next picture should display and when you click on PREV, the previous image should display."
This is what I wrote so far:
<html>
<head>
<title>Image Loop</title>
</head>
<body>
<img src="http://placekitten.com/500/200" id="image" style="height:150px; width:150px" />
<input type="button" value="Prev" name="previous_picture" onclick= nextImage();>
<input type="button" value="Next" name="next_picture"/>
<script>
function nextImage () {
var i = images.indexOf();
var imageSrc = document.getElementById("image").src=images[i];
for (i = weekdays.indexOf(day); i<weekdays.length; i++)
}
function prevImage () {
}
var images = new Array(
"http://placekitten.com/500/200",
"http://placekitten.com/499/200",
"http://placekitten.com/501/200",
"http://placekitten.com/500/199"
);
</script>
</body>
</html>
* the image should loop back around when it gets to the end of the array. I just don't know what I'm doing... :( *
Do some more investigations, this really shows too little effort.
I'll give you some pointers.
Javascript: Generic get next item in array
Javascript knows the modulus operation:
https://msdn.microsoft.com/nl-nl/library/9f59bza0(v=vs.94).aspx
prev = (index + length - 1 ) % length
next = (index + 1 ) % length
prev needs prevImage() and next needs nextImage() functions
etc.
Jsfiddle of a solution, using a small bit of jquery:
https://jsfiddle.net/cchhymtx/
Javascript:
var images = new Array(
"http://placekitten.com/500/200",
"http://placekitten.com/499/200",
"http://placekitten.com/501/200",
"http://placekitten.com/500/199");
function getCurrentImageIndex() {
return images.indexOf(document.getElementById("image").src);
}
function next() {
nextImage = (getCurrentImageIndex() + 1) % images.length;
document.getElementById("image").src = images[nextImage];
}
function prev() {
nextImage = (getCurrentImageIndex() - 1 + images.length) % images.length;
document.getElementById("image").src = images[nextImage];
}
You have a few things off here.
To start with, take a look at how Array.indexOf() works: http://www.w3schools.com/jsref/jsref_indexof_array.asp
What are you trying to attempt with:
for (i = weekdays.indexOf(day); i<weekdays.length; i++)
After you find the index of the picture that is current, if index+1 would be greater than or equal to the length of the images array, then set index to 0.
You can accomplish it by using the following code
<script language="JavaScript" type="text/JavaScript">
var imgArray = new Array(
"11011_1.jpg","11011_2.jpg","11011_3.jpg","11011_4.jpg","11011_5.jpg"
);
baseURL = "http://www.planet99.com/pix";
numImages = 5;
curImage = 1;
function f_slideshow( xflip ) {
curImage = curImage + xflip;
if (curImage > numImages)
{ curImage = 1 ; }
if (curImage == 0)
{ curImage = numImages ; }
document.images[2].src = baseURL + '/' + imgArray[curImage - 1];
}
</script>
Click on the buttons to flip through the photos - allow a few seconds for
each photo to load.
<input type="button" value="<< Prev" name="cb_prev"
onclick="f_slideshow(-1)">
<input type="button" value="Next >>" name="cb_next"
onclick="f_slideshow(1)">
<img src='http://www.planet99.com/pix/11011_1.jpg'>
My script, stored as a separate js file:
function randomNumber(len) {
var randomNumber;
var n = '';
for(var count = 0; count < len; count++) {
randomNumber = Math.floor(Math.random() * 10);
n += randomNumber.toString();
}
return n;
}
var finalSequence = randomNumber(9);
document.write('<INPUT TYPE=TEXT NAME="ACCOUNT" VALUE='+finalSequence +' MAXLENGTH=16 SIZE=16>');
I have included this td tag in my html file:
<td align=left><FONT FACE="Arial,Helvetica"><script src="nexgen.js"></script>
Do you suggest that I write my script inside the html file itself?
I would like to display the generated random number using an input tag, such as that below. How do I do this?
<INPUT TYPE=TEXT NAME="ACCOUNT" VALUE= ??? MAXLENGTH=16 SIZE=16>
Update:
I am combining the JavaScript and html in one html file as follows. Please see if you can find any mistakes because the number generated is not being displayed on html page.
Javascript part:
function randomNumber(len) {
var randomNumber;
var n = '';
for(var count = 0; count < len; count++) {
randomNumber = Math.floor(Math.random() * 10);
n += randomNumber.toString();
}
document.getElementById("ACCOUNT").value = n;
return n;
}
HTML part:
<tr>
<td><FONT FACE="Arial,Helvetica" color="red"> Transaction ID: </font></td>
<td align=left>
<FONT FACE="Arial,Helvetica">
<script> randomNumber(9); </script>
<INPUT TYPE=TEXT NAME="ACCOUNT" ID="ACCOUNT" VALUE="" MAXLENGTH=16 SIZE=16 readonly>
</font>
</td>
</tr>
Assign an ID to your input element, then in your JavaScript, assign the generated value to that element.
function randomNumber(len) {
var randomNumber;
var n = '';
for (var count = 0; count < len; count++) {
randomNumber = Math.floor(Math.random() * 10);
n += randomNumber.toString();
}
return n;
}
document.getElementById("ACCOUNT").value = randomNumber(9);
<INPUT TYPE=TEXT NAME="ACCOUNT" ID="ACCOUNT" VALUE="" MAXLENGTH=16 SIZE=16>
Working jsFiddle.
BTW, if you want to generate a random number of a certain length, you can do it in much bigger chunks than one digit at a time, e.g.:
function longRandom(length) {
var n = '';
while (n.length < length) {
n += ('' + Math.random()).split('.')[1];
}
return n.substr(0, length);
}
console.log(longRandom(42)); // 134434793311713322660940870849409308530315
will do it in chunks of about 15 digits on each loop. :-)
A random number is generated using javascript and also passed in the input form tag in html using code similar to ones mentioned below.
Javascript :
function randomNumber(len) {
var randomNumber;
var n = '';
for(var count = 0; count < len; count++) {
randomNumber = Math.floor(Math.random() * 10);
n += randomNumber.toString();
}
return n;
}
window.onload = function() {
document.getElementById("ACCOUNT").value = randomNumber(9);
};
HTML part:
<INPUT TYPE=TEXT NAME="ACCOUNT" ID="ACCOUNT" VALUE="" MAXLENGTH=16 SIZE=16>
Something like this, but you can do that in different ways:
http://jsbin.com/hujefopa/1/edit
function rand(len){
return Math.floor(Math.random() * Math.pow(10, len));
}
function setRand(){
document.getElementById('rand').value = rand(9);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body onload="setRand()">
<input type="text" id="rand">
</body>
</html>
Please note that:
If your script is small, it's better to put it inside the page itself rather than importing a new file (new request to the server).
Using document.write is not recommended. See this question.
To update the value of html input you can use:
document.getElementById('id-of-your-input-element').value = newValue;
or using jQuery:
$('#id-of-your-input-element').val(newValue);
HTML PART
<tr>
<td><FONT FACE="Arial,Helvetica" color="red"> Transaction ID: </font></td>
<td align=left>
<FONT FACE="Arial,Helvetica">
<INPUT TYPE=TEXT NAME="ACCOUNT" ID="ACCOUNT" VALUE="" MAXLENGTH=16 SIZE=16
readonly>
</font>
</td>
</tr>
JavaScript Part
<script>
document.getElementById('ACCOUNT').value=Math.floor(Math.random() * 10);
</script>