Random Image Display, Without Repeat, with Javascript - javascript

I know there are already a few questions like this, but I just can't seem to apply any of the answers (this is my first time making anything like this at all). I currently have a page that, when a button is pushed, a random image appears (thanks to some of the great posts on here, this is actually working). My issue is, the random number has a lot of repeats prior all the images being seen. I am wanting to make it where all images are seen (in a random order) before any duplicates. This is what is in the body:
<form name="imageForm">
<table border=3>
<tr align="center">
<td>
<input onclick="displayImage();" type=button value="Click Here">
</td>
</tr>
<tr>
<td>
<img src="blank.jpg" name="canvas" />
</td>
</tr>
</table>
</form>
Here is the script:
<script language="javascript">
var imagesArray = [
'images/img-1.jpg',
'images/img-2.jpg',
'images/img-3.jpg',
'images/img-4.jpg',
'images/img-5.jpg',
];
function displayImage(){
var num = Math.floor(Math.random() * (imagesArray.length));
document.canvas.src = imagesArray[num];
}
</script>
From what I have read, the way to do this would be to add a spice, and have shown images dropped into a new array, then once the original array equals 0, then have it reset. Try as I might, I have not been able to successfully integrate that into my code :( . This is what I ended up with (which does nothing, and breaks the function entirely):
<script>
var imagesArray = [
'images/img-1.jpg',
'images/img-2.jpg',
'images/img-3.jpg',
'images/img-4.jpg',
'images/img-5.jpg',
];
var shownImages = []
function displayImage(){
var num = Math.floor(Math.random() * (imagesArray.length));
document.canvas.src = imagesArray[num];
shownImages.unshift(imagesArray.splice(num,num+1));
if(images.length == 0){
images.Array = shownImages;
shownImages = [];
return shownImages[0];
}
</script>
Another method mentioned seemed to be to have a function that shuffled the images first, then displayed them in the shuffled order, then reshuffled and repeated, but I got even less far with that.
There also seems to be some question on whether the random number max should be imagesArray.length by itself, or +1 or -1. I am sure there are a number of other issues with this as well, but like I said, this is my first attempt. Any help is appreciated.

You should keep track of the numbers that you have generated, and if its a repeat then get a new number.
<script language="javascript">
var imagesArray = [
'images/img-1.jpg',
'images/img-2.jpg',
'images/img-3.jpg',
'images/img-4.jpg',
'images/img-5.jpg',
];
var usedImages = {};
var usedImagesCount = 0;
function displayImage(){
var num = Math.floor(Math.random() * (imagesArray.length));
if (!usedImages[num]){
document.canvas.src = imagesArray[num];
usedImages[num] = true;
usedImagesCount++;
if (usedImagesCount === imagesArray.length){
usedImagesCount = 0;
usedImages = {};
}
} else {
displayImage();
}
}
</script>

Related

"Writing" inside a HTML page using JS and JS scope

I'm developing a program which basically just receives input from the user twice (risk carrier and sum, but that's just a placeholder to make my program less abstract), groups those two values together and then repeats the contents in a loop. See the code below.
<head>
<script type="text/javascript">
function fillArray(){
document.getElementById("danke").innerHTML = "Thanks for specifying the amount of entries.";
var numberOfEntries = parseInt(document.getElementById('input0').value);
var i = 0;
var myArrA = [];
var myArrB = [];
var x = " ";
while(i<numberOfEntries){
var neuRT = prompt("Enter a risk carrier");
myArrA.push(neuRT);
var neuRH = prompt("Enter a risk sum");
myArrB.push(neuRH);
i++;
}
for(i = 0; i<anzahlEintraege; i++){
x = myArrA[i] + " carries a risk of " + myArrB[i];
document.getElementById("test").innerHTML = x;
}
}
</script>
</head>
<body>
<h1>risk assessment</h1>
<input type="text" id="input0" />
<button type="button" onclick="fillArray()">Number of entries</button> <p id="danke"></p>
<button type="button" onclick="untilNow()">Show all entries so far</button>
<br />
<br />
<div id="test"></div>
</body>
</html>
My issues are:
1.) I want to display the array by writing into an HTML element, which I attempted in the for-loop. Pop-ups are to be avoided. How can I loop through HTML elements, such as demo1, demo2, demo3 etc.? I can't just write <p id="demo" + i></p>. What other options are there?
2.) Say I want to make use of the untilNow() function. The scope of my arrays is limited to fillArray(). Do I need to "return" the arrays to the untilNow() function as parameters?
Thanks everyone!!!
The problem with your current code is that you're replacing the html by the last value in every loop. You're using = rather than +=. So, a quick fix would be to replace:
document.getElementById("test").innerHTML = x;
by:
document.getElementById("test").innerHTML += x;
An example of how you could wrap an array of strings in HTMLElements and add them to your document (note that there are many other ways/libraries to achieve the same result):
var myStrings = ["Hello", "stack", "overflow"];
// Two performance rules:
// 1. Use a fragment to prevent multiple updates to the DOM
// 2. No DOM queries in the loop
var newContent = myStrings.reduce(function(result, str) {
var li = document.createElement("li");
var txt = document.createTextNode(str);
li.appendChild(txt);
result.appendChild(li);
return result;
}, document.createDocumentFragment());
// Actually add the new content
document.querySelector("ul").appendChild(newContent);
<ul class="js-list"></ul>

Creating Lucky 7's game using raw Javascript, what am I doing wrong?

I've decided to come to the wise ones of stack overflow, in hopes of gaining some insight to my problem. I'm a newbie to javascript, and the school i'm attending has given us an assignment to create a Lucky 7's program.
The instructions are that a user places a bet, clicks play, and two dice are rolled. If the dice total is 7, $4 is added to the users bet, if not, $1 is subtracted.
Once the player reaches $0, a table showing the results is displayed. The results shown are "Starting Bet", "Total Rolls Before Going Broke", "Highest Amount Won", and "Roll count from Highest Amount Won".
So far I've got most of it working, but the results are always similar: All results are the same as the starting bet, except the highest amount won, that is always 1 less than the starting bet.
Could it have something to do with my while loop? I've tried moving things around and changing the assignment operators to += instead of bet = bet + 4, but it's always the same. Any input would be much appreciated!
function hideResults() {
document.getElementById("results").style.display = "none";
}
function play() {
var startingBet = document.getElementById("betInput").value;
var bet = startingBet;
var dice1 = Math.floor(Math.random() * 6) + 1;
var dice2 = Math.floor(Math.random() * 6) + 1;
var diceRoll = dice1 + dice2;
var betsArray = [];
while (bet > 0) {
if(diceRoll != 7) {
bet -= 1
} else {
bet += 4
}
betsArray.push(bet)
}
var rollCounter = betsArray.length;
var highestAmount = Math.max.apply(Math, betsArray);
var highestPosition = betsArray.indexOf(highestAmount);
var rollsFromHighest = rollCounter - highestPosition;
function showResults() {
document.getElementById("results").style.display = "inline";
document.getElementById("playButton").innerHTML = "Play Again";
document.getElementById("resultsBet").innerHTML = "$" + startingBet +".00";
document.getElementById("resultsRollCounter").innerHTML = rollCounter;
document.getElementById("resultsHighestHeld").innerHTML = "$" + highestAmount + ".00";
document.getElementById("resultsRollsFromHighest").innerHTML = rollsFromHighest;
};
showResults();
}
The HTML:
<!DOCTYPE html>
<html>
<head>
<title>Lucky Sevens</title>
<link href="css/LuckySevensStyles.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="js/LuckySevensV1.js"></script>
</head>
<body onload="hideResults()">
<!-- BET STUFFS -->
<div id="gameDiv">
<h1>Lucky Sevens</h1>
<span>Starting Bet:<input type="number" name="Starting Bet" id="betInput" placeholder="$0.00"></span>
<br/>
<button onclick="play()" id="playButton">Play</button>
</form>
</div>
<!-- RESULT STUFFS -->
<div id="results">
<table>
<caption><h2>Results</h2></caption>
<tr>
<th>Starting Bet</th>
<th id="resultsBet"></th>
</tr>
<tr>
<td>Total Rolls Before Going Broke</td>
<td id="resultsRollCounter"></td>
</tr>
<tr>
<td>Highest Amount Won</td>
<td id="resultsHighestHeld"></td>
</tr>
<tr>
<td>Roll Count at Highest Amount Won</td>
<td id="resultsRollsFromHighest"></td>
</tr>
</table>
</div>
</body>
</html>
The VARIABLE diceRoll will not re calculate the random number. You should reassign the random numbers within the loop after you push the updated bet to the array.
If you want, you could write a function to handle this, but it's just as easy to copy and paste your lines from the dice1 & dice2 and diceRoll var instantiations into the loop after the if block

Pass variables to code <input type="image" src="imageSrc;" >

hope someone can help a noob. Many thanks in advance.
I have an index page with links to hundreds of other pages holding song words.
I have built each song page but it would be MUCH simpler to have one MASTER page that took a variable from the index page and found the corresponding words (which exist as png graphics.)
I have sorted Step 1 - I can pass a variable from the index page to the master page using:
<a href="javascript: window.open('MUSIC/beatles/mastertest2.html?song=ER', '_parent')">
where song=ER is the variable to display the words for Eleanor Rigby. For Step 2, I can also retrieve that information in the master page with:
var imageSrc = (qs("song")+".png"); document.write(imageSrc);
which will display the text ER.png which is the name of the image I want to display.
For Step 3 I am trying to get this same variable read into:
<input type="image" src="imageSrc;">
to display the picture. I have searched this and other forums for days now and nothing suggested works for me. I could be missing out an essential early step in the coding?
Update:
My master html file has this code to retrieve the variable:
function qs(search_for) {
var query = window.location.search.substring(1);
var parms = query.split('&');
for (var i=0; i<parms.length; i++) {
var pos = parms[i].indexOf('=');
if (pos > 0 && search_for == parms[i].substring(0,pos)) {
return parms[i].substring(pos+1);;
}
}
return "";
}
And it uses this code to disply the variable (appended with .png) just to prove to me that it is getting through:
var imageSrc = (qs("song")+".png");
document.write(imageSrc);
Then I am trying to feed the variable into a routine to display the png selected. The next script doesn't work but I am thrashing about trying anything right now:
var imageSrc = (qs("song")+".png");
document.write(imageSrc);
<input type="image" src="#imageSrc;" border="0" value="Notes" onClick="placeIt(); showIt()">
<input id="song-image" type="image">
var imageSrc = 'ER.png';
var input = document.getElementById('song-image');
input.src = imageSrc;
If you have already <input type="image"> in your HTML page, you must add an id and then set it's src attribute with
HTML:
<input id="song-image" type="image">
JS:
var imageSrc = 'http://www.lorempixel.com/200/100';
var input = document.getElementById('song-image');
input.src = imageSrc;
JSFiddle for testing.
If I understood you right, its very simple. Are you looking for this?
var input = document.createElement('input');
input.type = 'image';
input.src = imageSrc;
document.body.appendChild(input);
If you can print the variable imageSrc using document.write, then you can use it like shown above.

How would I capture the 'alt' attribute for the images a user selects from this slideshow?

How can I modify this script to capture the 'alt' attribute for the images a user selects in a slideshow?
This code displays a series of 20 pairs of images and asks users to select their preferences. Each time the user clicks one of the 'Select' buttons, the 'manipulateDOM()' function advances to the next set of items in the the text and image arrays. However, since it's not set up as a typical form field, I'm having difficulty figuring out how to capture the value of each selection so that it can be submitted to the database with the rest of the form values.
I tried creating a function with the click() method to (at the very least) capture the src value, but I can't get the syntax right so that it can run in conjunction with the 'manipulateDOM()' function. I'd also much rather capture the 'alt' attribute, but I couldn't figure out how to do that.
Function I was experimenting with:
$(document).ready(function () {
$("#buttons").click(function () {
var imgvalue = $("#imgtrendy").attr("src");
$("#picval").text(imgvalue);
document.write(imgvalue + ', ');
});
});
Existing Code:
Javascript - manipulateDOM() and manipulateDOM1() functions
var NumberOfImages = 3 - 1; //-1 because array members starts from 0
var trendy = new Array(NumberOfImages);
trendy[0] = "files/set1/A1.jpg";
trendy[1] = "files/set1/B1.jpg";
trendy[2] = "files/set1/C1.jpg";
var imgNumber = 1; //array key of current image
var NumberOfImages = 3 - 1;
var classic = new Array(NumberOfImages);
classic[0] = "files/set1/A2.png";
classic[1] = "files/set1/B2.jpg";
classic[2] = "files/set1/C2.jpg";
var classicNumber = 1;
var text = 3 - 1;
var text = new Array;
text[0] = "Which would you be more likely to wear?"
text[1] = "Which look is more you?"
text[2] = "Which would you rather wear?"
var textNumber = 1;
function manipulateDOM() {
changeObjects();
NextImage();
}
function changeObjects() {
document.getElementById("question").innerHTML = text[textNumber];
}
function NextImage() {
if (imgNumber < NumberOfImages) //Stop moving forward when we are out of images
{
imgNumber++;
document.images["taste"].src = trendy[imgNumber];
document.images["taste1"].src = classic[imgNumber];
textNumber++;
document.getElementById["question"].innerHTML = text[textNumber];
document.getElementById["selectButton"].innerHTML = text[textNumber];
}
}
function manipulateDOM1() {
changeObjects();
NextImage1();
}
function NextImage1() {
if (imgNumber < NumberOfImages)
{
imgNumber++;
document.images["taste"].src = trendy[imgNumber];
document.images["taste1"].src = classic[imgNumber];
textNumber++;
document.getElementById["question"].innerHTML = text[textNumber];
document.getElementById["selectButton"].innerHTML = text[textNumber];
}
}
HTML
<form id="taste" name="taste" method="post" action="taste-exec.php" >
<h2 id="question"> Which would you be more likely to wear?</h2>
<table><tr>
<td><img id="imgtrendy" src="files/set1/A1.jpg" name="taste" value="trendy[1]" /></td>
<td><img id="imgclassic" src="files/set1/A2.png" name="taste1" value="classic[1]" /></td></tr>
<tr id="buttons">
<td><img id="trendyButton" alt"Select" src="files/Select.jpg" onclick="javascript:manipulateDOM()"></td>
<td ><img id="classicButton" alt"Select" src="files/Select.jpg" onclick="javascript:manipulateDOM1()"></td>
</tr><tr>
<td id="picval"></td>
<td><input name="answer" id="answer" type="text" /></td>
</tr></table>
</form>
You get the alt attribute using also the attr method and alt as parameter, just like you are already doing with src. You could try:
function changeObjects() {
document.getElementById("question").innerHTML = text[textNumber];
var imgvalue = $("#imgtrendy").attr("alt");
$("#picval").text(imgvalue);
}
Edit: Example of keeping data in one single array
//to save it
var alt = $("#imgtrendy").attr("alt");
var fileName= 'someValue';//populate accordingly
var myArray[index] = alt + '|' + fileName;
//to retrieve it
var bothValues = myArray[index].split('|'); //gives you an array
alt = bothValues[0] //contains alt at index 0
fileName = bothValues[1] //contains fileName at index 1

getElementById() .innerHTML/.src

I'm trying to create a simple javascript game for college and am having trouble getting what i want to display on screen.
my script is as follows:
var qArray = new Array();
qArray[0] = {image:"Images/q1.png"};
qArray[1] = {image:"Images/q2.png"};
qArray[2] = {image:"Images/q3.png"};
qArray[3] = {image:"Images/q4.png"};
qArray[4] = {image:"Images/q5.png"};
var count = 0;
var question = qArray.splice(count,1);
when i use this i get "undefined":
document.getElementById("question").innerHTML = question.image;
and when i use this i get nothing:
document.getElementById("question").src = question.image;
my html is just a simple div like so:
<div id = "question" align = "center">
</div>
i need to have the "count" variable because it increments to show the next image for the next question
if anyone could help that would be great
Here is a working Fiddle. qArray.splice() doesn't work because it actually removes that element from the array and returns a new array while you were just looking for a specific index in the array (not to mention you just deleted the element you were looking for)
This works. I used a random imgur image to show that it does indeed load.
<html><head></head><body>
<img src="" id="question"></img>
<script type="text/javascript">
var qArray = new Array();
qArray[0] = {image:"http://i.imgur.com/pGpmq.jpg"};
qArray[1] = {image:"Images/q2.png"};
qArray[2] = {image:"Images/q3.png"};
qArray[3] = {image:"Images/q4.png"};
qArray[4] = {image:"Images/q5.png"};
var count = 0;
var question = qArray[count];
document.getElementById('question').src = question.image;
</script>
</body>
</html>

Categories