I am struggling a bit with this random image javascript even though I sense the answer is quite simple. My code generates four letters (images) at a time. How do I get the code to regenerate new letters instead of adding four additional letters (images)?
Here is a Jsfiddle also.
<script>
function getRandomImage() {
//declare an array to store the images
var randomImage = new Array();
//insert the URL of images in array
randomImage[0] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/a.png";
randomImage[1] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/b.png";
randomImage[2] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/c.png";
randomImage[3] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/d.png";
randomImage[4] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/e.png";
randomImage[5] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/f.png";
randomImage[6] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/g.png";
randomImage[7] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/h.png";
randomImage[8] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/i.png";
randomImage[9] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/j.png";
randomImage[10] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/k.png";
randomImage[11] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/l.png";
randomImage[12] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/m.png";
randomImage[13] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/n.png";
randomImage[14] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/o.png";
randomImage[15] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/p.png";
randomImage[16] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/q.png";
randomImage[17] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/r.png";
randomImage[18] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/s.png";
randomImage[19] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/t.png";
randomImage[20] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/u.png";
randomImage[21] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/v.png";
randomImage[22] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/w.png";
randomImage[23] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/x.png";
randomImage[24] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/y.png";
randomImage[25] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/z.png";
//loop to display five randomly chosen images at once
for (let i=0; i< 4; i++) {
//generate a number and provide to the image to generate randomly
var number = Math.floor(Math.random()*randomImage.length);
//print the images generated by a random number
document.getElementById("result").innerHTML += '<img src="'+ randomImage[number] +'" style="height:150px";/>';
}
}
</script>
<body>
<h1> GENERATE YOUR LETTERS... </h1>
<!-- call user-defined getRandomImage function to generate image -->
<center><button onclick = "getRandomImage()" class="btn btn-white btn- animate">Let's Go!</button></center>
<br> <br>
<span id="result" align="center"> </span>
You can add document.getElementById('result').innerHTML = "" before your for loop to clear the result div before adding 4 new items.
You can also reduce your code a lot by using a for loop to generate the image URLs.
var letters = 'abcdefghijklmnopqrstuvwxyz'.split('');
for (let i = 0; i < letters.length; i++) {
randomImage.push(`http://www.englishclass.dk/_themes/englishclass/img/scrabble/${letters[i]}.png`)
}
document.getElementById('result').innerHTML = " " before for loop
<script>
function getRandomImage() {
//declare an array to store the images
var randomImage = new Array();
//insert the URL of images in array
randomImage[0] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/a.png";
randomImage[1] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/b.png";
randomImage[2] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/c.png";
randomImage[3] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/d.png";
randomImage[4] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/e.png";
randomImage[5] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/f.png";
randomImage[6] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/g.png";
randomImage[7] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/h.png";
randomImage[8] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/i.png";
randomImage[9] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/j.png";
randomImage[10] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/k.png";
randomImage[11] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/l.png";
randomImage[12] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/m.png";
randomImage[13] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/n.png";
randomImage[14] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/o.png";
randomImage[15] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/p.png";
randomImage[16] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/q.png";
randomImage[17] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/r.png";
randomImage[18] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/s.png";
randomImage[19] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/t.png";
randomImage[20] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/u.png";
randomImage[21] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/v.png";
randomImage[22] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/w.png";
randomImage[23] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/x.png";
randomImage[24] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/y.png";
randomImage[25] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/z.png";
//loop to display five randomly chosen images at once
document.getElementById("result").innerHTML="";
for (let i=0; i< 4; i++) {
//generate a number and provide to the image to generate randomly
var number = Math.floor(Math.random()*randomImage.length);
//print the images generated by a random number
document.getElementById("result").innerHTML += '<img src="'+ randomImage[number] +'" style="height:150px";/>';
}
}
</script>
<body>
<h1> GENERATE YOUR LETTERS... </h1>
<!-- call user-defined getRandomImage function to generate image -->
<center><button onclick = "getRandomImage()" class="btn btn-white btn- animate">Let's Go!</button></center>
<br> <br>
<span id="result" align="center"> </span>
Add following code at starting of the function definition :
document.getElementById("result").innerHTML = "";
Like this
<script>
function getRandomImage() {
document.getElementById("result").innerHTML = "";
//declare an array to store the images
var randomImage = new Array();
//insert the URL of images in array
randomImage[0] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/a.png";
randomImage[1] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/b.png";
randomImage[2] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/c.png";
randomImage[3] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/d.png";
randomImage[4] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/e.png";
randomImage[5] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/f.png";
randomImage[6] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/g.png";
randomImage[7] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/h.png";
randomImage[8] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/i.png";
randomImage[9] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/j.png";
randomImage[10] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/k.png";
randomImage[11] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/l.png";
randomImage[12] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/m.png";
randomImage[13] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/n.png";
randomImage[14] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/o.png";
randomImage[15] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/p.png";
randomImage[16] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/q.png";
randomImage[17] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/r.png";
randomImage[18] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/s.png";
randomImage[19] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/t.png";
randomImage[20] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/u.png";
randomImage[21] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/v.png";
randomImage[22] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/w.png";
randomImage[23] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/x.png";
randomImage[24] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/y.png";
randomImage[25] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/z.png";
//loop to display five randomly chosen images at once
for (let i=0; i< 4; i++) {
//generate a number and provide to the image to generate randomly
var number = Math.floor(Math.random()*randomImage.length);
//print the images generated by a random number
document.getElementById("result").innerHTML += '<img src="'+ randomImage[number] +'" style="height:150px";/>';
}
}
</script>
<body>
<h1> GENERATE YOUR LETTERS... </h1>
<!-- call user-defined getRandomImage function to generate image -->
<center><button onclick = "getRandomImage()" class="btn btn-white btn- animate">Let's Go!</button></center>
<br> <br>
<span id="result" align="center"> </span>
As explained in "innerHTML += ..." vs "appendChild(txtNode)" appending new elements by doing innerHTML += '<img />' causes the browser to rebuild the entire container. This may cause performance issues depending on where, when and how often you call it. For the sake of completeness I'm providing the more performant example (a bit more verbose but in general better practice).
This should replace your for loop:
// Clear all childs from the container
const container = document.getElementById("result");
container.childNodes.forEach((child) => child.remove());
for (let i = 0; i < 4; i++) {
const number = Math.floor(Math.random() * randomImage.length);
// Create a new <img /> element and append it to the container
const image = document.createElement("img");
image.src = randomImage[number];
image.style.height = "150px";
container.append(image);
}
You can also get a random letter without splitting a string by using the method given in the top voted answer here. You can then simplify your code as the others have mentioned above to only a few lines.
I've commented the code below.
// Function triggered with onclick event
function getRandomImage() {
// Clear the previous letters
document.getElementById("result").innerHTML = "";
// Loop
for (let i = 0; i < 4; i++) {
// Generate random letter
letter = String.fromCharCode(97 + Math.floor(Math.random() * 26))
// Add image to #result
document.getElementById("result").innerHTML += '<img src="http://www.englishclass.dk/_themes/englishclass/img/scrabble/' + letter + '.png" style="height:150px";/>';
}
}
<h1> GENERATE YOUR LETTERS... </h1>
<center>
<button onclick="getRandomImage()" class class="btn btn-white btn-animate">
Let's Go!
</button>
</center>
<br>
<br>
<span id="result" align="center"> </span>
Related
Hello here I'm trying to Output my function on two separate divs in my project but if I simply output the same I'd it cancels the whole code and nulls the output here is the code.
<script>
function randomString() {
//initialize a variable having alpha-numeric characters
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
//specify the length for the new string to be generated
var string_length = 10;
var randomstring = '';
//put a loop to select a character randomly in each iteration
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
//display the generated string
document.getElementById("randomfield").innerHTML = randomstring;
}
</script>
Then on the body I use
<body onload="randomString();">
<div>
<p id="randomfield"></p>
</div>
</body>
The thing is I want to Output the same string on the page but on a different div maybe at the footer but if I proceed to add
<body onload="randomString();">
<div>
<p id="randomfield"></p>
</div>
<hr>
<footer>
<p id="randomfield"></p>
</footer>
</body>
On the same page it cancels the whole code and nullifies the output. How do I fix this i barely have knowledge of Js
You are using the same id in both areas. You have to specify different id to have them work:
function randomSSSSSString() {
//initialize a variable having alpha-numeric characters
var charssssss = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
//specify the length for the new string to be generated
var sssssstring_length = 10;
var randomsssssstring = '';
//put a loop to select a character randomly in each iteration
for (var i = 0; i < sssssstring_length; i++) {
var rrrrrrnum = Math.floor(Math.random() * charssssss.length);
randomsssssstring += charssssss.substring(rrrrrrnum, rrrrrrnum + 1);
}
//display the generated string
document.getElementById("rrrrrrandomfield").innerHTML = randomsssssstring;
document.getElementById("rrrrrrandomfield2").innerHTML = randomsssssstring;
}
<body onload="randomSSSSSString();">
<div>
<p id="rrrrrrandomfield"></p>
</div>
<hr>
<footer>
<p id="rrrrrrandomfield2"></p>
</footer>
</body>
This is happening because you're using same "id" more than once, which is not valid.
You can change the id to class instead and can use querySelectorAll to loop through each element consisting of that class to display your result.
function randomSSSSSString() {
//initialize a variable having alpha-numeric characters
var charssssss = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
//specify the length for the new string to be generated
var sssssstring_length = 10;
var randomsssssstring = '';
//put a loop to select a character randomly in each iteration
for (var i=0; i<sssssstring_length; i++) {
var rrrrrrnum = Math.floor(Math.random() * charssssss.length);
randomsssssstring += charssssss.substring(rrrrrrnum,rrrrrrnum+1);
}
//display the generated string
var i_want_show_here = document.querySelectorAll(".rrrrrrandomfield")
Array.prototype.forEach.call(i_want_show_here, function(el) {
el.innerHTML = randomsssssstring
});
}
<body onload="randomSSSSSString();">
<div>
<p class="rrrrrrandomfield"></p>
</div>
<hr>
<footer>
<p class="rrrrrrandomfield"></p>
</footer>
</body>
I think you can solve this by creating dynamic p tag with same id. There is no var datatype in javascript change it to let.
function randomString() {
let characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
let randnum = document.getElementById("randnum")
let stringLength = 10;
let tempRandomString = '';
for (let i = 0; i < stringLength; i++) {
let randNum = Math.floor(Math.random() * characters.length);
tempRandomString += characters.substring(randNum, randNum + 1);
}
for (var i = 0; i < 2; i++) {
const elem = document.createElement(`p`);
elem.id = tempRandomString;
elem.innerText= tempRandomString;
randnum.appendChild(elem);
}
}
<html>
<title>Web Page</title>
<head>
</head>
<body onload="randomString();">
<div id="randnum">
</div>
</body>
</html>
I am trying to create a form which will generate different levels of forms based on the user input.
An example of this is
"How many levels are there?" -User input 3-
Three separate levels will be generated each with the same questions. In this there will be a question asking "How many objects are there?" the same will happen here in that multiple options will be generated.
Rough sketch of how the form would be displayed
The problem I've been having with this is allocating ids and then being able to fetch them after so that they can be referenced for use and MySQL later down the line.
function generateForm(){
var number = document.getElementById('number_of_levels').value;
var div = document.getElementById('levels');
// div.innerHTML += " " +number;
var heading = document.createElement("P");
heading.innerHTML = "Level " + number;
document.getElementById('levels').appendChild(heading);
var objects = document.createElement("P");
objects.innerHTML = "How many objects is the badge comprised of?";
document.getElementById('levels').appendChild(objects);
var num_objects_input = document.createElement("input");
num_objects_input.type = "number";
num_objects_input.id = "number_objects" +number;
document.getElementById('levels').appendChild(num_objects_input);
//num_objects.onchange = function(){addObject(num_objects.id)};
//div for the following levels
var ind_levels_div = document.createElement("div");
ind_levels_div.id = "level_" +number;
document.getElementById('levels').appendChild(ind_levels_div);
num_objects_input.onchange = function(){additionalObject()};
}
function additionalObject(){
var number = document.getElementById("number_objects" +number).value;
var objects_number = document.createElement("P");
objects_number.innerHTML = "Object " + number;
document.getElementById("level_" +number).appendChild(objects_number);
}
The result I'm getting is the form won't generate any Object form elements but will make the Levels.
For building the form this code works fine. If you want to retrieve data then you should add a name attribute what data you want to retrieve.
function generateForm() {
var number = 0;
number = document.getElementById('number_of_levels').value;
var div = document.getElementById('levels');
// div.innerHTML += " " +number;
if (number > 0) {
document.getElementById('levels_btn').setAttribute('disabled', 'disabled');
}
for (let index = 0; index < number; index++) {
var heading = document.createElement("h4");
heading.innerHTML = "Level " + (index + 1);
document.getElementById('levels').appendChild(heading);
var objects = document.createElement("p");
objects.innerHTML = "How many objects is the badge comprised of?";
document.getElementById('levels').appendChild(objects);
var num_objects_input = document.createElement("input");
num_objects_input.type = "number";
num_objects_input.id = "number_objects" + (index + 1);
document.getElementById('levels').appendChild(num_objects_input);
var submit = document.createElement("button");
submit.type = "button";
submit.innerHTML = 'objects';
submit.id = "submit" + (index + 1);
submit.onclick = additionalObject;
document.getElementById('levels').appendChild(submit);
var objectdiv = document.createElement("div");
objectdiv.id = "objects_level" + (index + 1);
objectdiv.className = 'objects_level';
document.getElementById('levels').appendChild(objectdiv);
}
}
function additionalObject() {
//console.log(Number(this.id.replace("submit", "")));
var pos = Number(this.id.replace("submit", ""));
var number = document.getElementById('number_objects' + pos).value;
for (let index = 0; index < number; index++) {
var objects_number = document.createElement("p");
objects_number.innerHTML = "Object " + (index + 1);
document.getElementById("objects_level" + pos).appendChild(objects_number);
}
}
.levels {
padding-left: 20px;
}
.objects_level {
padding-left: 40px;
}
<h3>Level</h3>
<form action="/" method="get">
<input type='number' name='number_of_levels' id='number_of_levels' />
<button type='button' id='levels_btn' onclick='generateForm()' />Levels</button>
<div id='levels' class='levels'></div>
<br><br>
<button type="submit">Submit Form</button>
</form>
You can read the article https://www.w3schools.com/tags/att_form_action.asp for getting the idea of how from action works according to retrieve the data
I'm trying to output a random image from my array and then remove it from the array afterwards for a matching game. I'm new to programming in general and I've seen (what I'm sure are) easier ways of doing it but nothing I understand yet so I'm trying it this way. The problem is that I can't get an image to print out and I'm not sure why. Any help would be appreciated! thanks!
HTML
<script>
printImage(); Sites.splice(r,1);
</script>
JS
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = 'img0.jpg';
...
imgArray[23] = new Image();
imgArray[23].src = 'img23.jpg';
ImageRotation = imgArray.length;
FirstHalf = '<img src="img';
LastHalf = '.jpg" style="width:100px; height: 100px;">';
function printImage() {
var r = Math.ceil(Math.random() * ImageRotation);
document.write(FirstHalf + r + LastHalf);
}
This is how you can do what you are tried to achieve:
I've used setInterval to demonstrate.
Fiddle
HTML:
<img src="http://dummyimage.com/100x100/252799/fff.png&text=one" />
JavaScript:
var imgs = ['http://dummyimage.com/100x100/252799/fff.png&text=one', 'http://dummyimage.com/100x100/252799/fff.png&text=two', 'http://dummyimage.com/100x100/252799/fff.png&text=three', 'http://dummyimage.com/100x100/252799/fff.png&text=four', 'http://dummyimage.com/100x100/252799/fff.png&text=five', 'http://dummyimage.com/100x100/252799/fff.png&text=six', 'http://dummyimage.com/100x100/252799/fff.png&text=seven', 'http://dummyimage.com/100x100/252799/fff.png&text=eight', 'http://dummyimage.com/100x100/252799/fff.png&text=nine', 'http://dummyimage.com/100x100/252799/fff.png&text=ten'];
setInterval(function() {
var im = document.getElementsByTagName('img')[0];
im.src = imgs[Math.round(Math.random() * (imgs.length - 1))];
}, 1000);
Here is another way of setting the image, based on #chipChocolate.py's answer, and addressing OP's requirement that each image is removed from the list. Instead of changing the first image in the HTML, it rewrites the inner HTML within a <div> container.
<html>
<head>
<script type="text/javascript">
var imgs = ['http://dummyimage.com/100x100/252799/fff.png&text=one', 'http://dummyimage.com/100x100/252799/fff.png&text=two', 'http://dummyimage.com/100x100/252799/fff.png&text=three', 'http://dummyimage.com/100x100/252799/fff.png&text=four', 'http://dummyimage.com/100x100/252799/fff.png&text=five', 'http://dummyimage.com/100x100/252799/fff.png&text=six', 'http://dummyimage.com/100x100/252799/fff.png&text=seven', 'http://dummyimage.com/100x100/252799/fff.png&text=eight', 'http://dummyimage.com/100x100/252799/fff.png&text=nine', 'http://dummyimage.com/100x100/252799/fff.png&text=ten'];
var pictures = imgs.length;
var picim =[];
for (var i=0; i<pictures; i++)
picim [i] = i;
var num = 0; // current index of picture number
function randpic() {
if (pictures > 1) {
pictures--;
for (var i=num; i<pictures; i++) // remove current picture index
picim[i] = picim[i+1];
num = Math.floor(Math.random() * pictures);
var content = '<IMG src="' + imgs[picim [num]] + '" />';
document.getElementById('randpic').innerHTML = content;
}
}
</script>
</head>
<body>
<div id="randpic" onClick="javascript:randpic()">
<img src="http://dummyimage.com/100x100/252799/fff.png&text=one" />
</div>
</body>
</html>
I have five images in a folder of my computer and I'm trying to create a script that display an image on the screen and when I click a button the image changes.
The javaScript code:
function cambiaimagen()
{
var i=1;
var direcciones = new
Array("imagen1.jpg","imagen2.jpg","imagen3.jpg","imagen4.jpg","imagen5.jpg");
var vusr = document.getElementById('imgs').value;
document.getElementById('imgs').innerHTML = vusr;
}
The HTML code:
<div id="contenedor">
<div id="img">
<img id="imgs" src="imagen1.jpg"/>
</div>
<button type="button">Anterior</button>
<button type="button" onclick = 'cambiaimagen()'>Siguiente</button>
</div>
When I run the script I watch the image 1 and the buttons. But when I click Siguiente button I don't watch the following image of array direcciones.
How can I watch it?
Thanks.
Replace your previous JavaScript code with this:
var cnt = 1;
var direcciones = new Array("imagen1.jpg","imagen2.jpg","imagen3.jpg","imagen4.jpg","imagen5.jpg");
function cambiaimagen(){
if(cnt != direcciones.length - 1){
cnt++;
}else{
cnt = 1;
}
document.getElementById('imgs').src = direcciones[cnt];
}
If the image names are in sequential number order (as they are in your example), you could use the following instead:
var cnt = 1;
var imgCnt = 5;
function cambiaimagen(){
if(cnt != imgCnt){
cnt++;
}else{
cnt = 1;
}
document.getElementById('imgs').src = "imagen" + cnt + "2.jpg";
}
Which I believe is a better method because there is no array with repetitive contents.
var direcciones = ["imagen1.jpg","imagen2.jpg","imagen3.jpg","imagen4.jpg","imagen5.jpg"];
var cnt = 0;
function cambiaimagen(){
document.getElementById("imgs").src = direcciones[(++cnt)%direcciones.length];
}
I’m trying to call a user input array.
I’m very new on Javascript but know I somehow need to reference the array (it is somewhere where I put the ???).
<script>
var arrayX =5;
var arrayY =1;
var array=new Array(arrayX);
var planetIndex=0;
for (x=0; x<array.length; x++)
{array [x] = new Array(arrayY);}
function insert(val1){
array[planetIndex][0]=val1;
planetIndex++;
document.getElementById('name').value = ''; };
function worldChange() {
var newplanet = ????????????
var whichWorld = Math.floor(Math.random()*newplanet.length);
return planetIndex[whichWorld];
var planets = document.getElementsByClassName("world-name")
for (var i=0; i < planets.length; i++) {
planets[i].innerHTML = worldChange();};
};
</script>
<body>
<div>
<form>
<input type="integer" id="name"/>
<input type="button" value="Add Planets" onclick="insert (this.form.name.value);"/>
</form>
<input type="button" value="See planet!" onClick="worldChange()" />
<br> Hello <span class="world-name">Earth!</span><br />
</div>
</body>
I got both elements of the script to work perfectly on my site so every time someone hits a button it changes the guy in the story. But as you see if pulls from the array I created. I want to pull from an array that a user creates so they could input their own list of names.
so this script works fine:
function newGuy() {
var guys = new Array ("Jeff", "Mike", "George", "Harold");
var whichGuy = Math.floor(Math.random()*guys.length);
return guys[whichGuy];}
var guy = document.getElementsByClassName("guy")
for (var i=0; i < guy.length; i++) {
guy[i].innerHTML = newGuy();}
And this script works alone:
var arrayX =5;
var arrayY =1;
var array=new Array(arrayX);
var guyIndex=0;
for (x=0; x<array.length; x++)
{array [x] = new Array(arrayY);}
function insert(val1){
array[guyIndex][0]=val1;
guyIndex++;
document.getElementById('name').value = ''; };
Just baffled on how to put them together.
There are a lot of problems with your script but to give you an idea on how to get it to work :
var planets = [];
// define how many planets there will be initially
var initialLength = 5;
// add the initital planets
for (x = 0; x < initialLength; x++) {
planets.push("planet" + x);
}
function insert() {
var planetToInsert = document.getElementById('name').value;
if (planetToInsert) {
// add the input to the array of planets
planets.push(planetToInsert);
document.getElementById('name').value = '';
} else {
alert("please enter a value");
}
}
function worldChange() {
// randomly pick an index
var whichWorld = Math.floor(Math.random() * planets.length);
document.getElementById('world-name').innerHTML = planets[whichWorld];
}
working sample here
For finding problems in you code jsFiddle can be of excellent help. Run JSlint to find the basic errors, put in alerts as poor mans debugging.
For a good javascript book I would recommend javascript patterns