Simple script doesn't run - javascript

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];
}

Related

Random image javascript

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>

How to exchange counter after delete field using plain javascript

I'm new in javascript. i have a JS function that add and remove input fields. its working fine with my JS function. But I want when delete a field its Id looks like:
I have
no. 1
no. 2
no. 3
After Delete 2:
no. 1
no. 2
already i got this answer:
Reset JavaScript Counter after Deleting a field
But i want it with plain javascript. Can anyone help?
<script>
var count = 1;
function add_new(){
count++;
var div1 = document.createElement('div');
div1.id = count;
var delLink = '<button type="button" onclick="deleteLink('+count+')" class="btn btn-primary">Delete</button>';
div1.innerHTML = document.getElementById('add_link1').innerHTML+delLink;
document.getElementById('add_link').appendChild(div1);
document.getElementById("input_link1").id = count;
document.getElementById("input_link2").id = count;
document.getElementById("input_link3").id = count;
}
function deleteLink(eleId){
var ele = document.getElementById(eleId);
var par = document.getElementById('add_link');
par.removeChild(ele);
}
</script>
After deleting an element call the following function to reset Id of existing elements and also reduce the count.
function reset_counter(deletedCount) {
for (var impactedElementId = deletedCount + 1; impactedElementId < count; impactedElementId++) {
var currentElement = document.getElementById(impactedElementId);
currentElement.id = impactedElementId - 1;
var button = currentElement.firstChild;
button.innerHTML = 'Delete ' + currentElement.id;
button.setAttribute('onclick', 'deleteLink(' + currentElement.id + ')');
}
count--;
}
The full code is available here: AddDeleteElements Sample Code

IE appendChild from array not working

I have an history feature for a particular,div on my website. Everything worked fine up to now, I was inserting HTML as strings from javascript and re-display them with .innerHTML. Now I try to clean up the javascript from all HTML strings and I have this problem: history browsing of the div works in FF, Chrome and some other, but not IE (8 to 11), can't understand why. Is it a cloneNode() or a reference issue I don't see ?
Below is a small script to reproduce the behaviour, you can play with here: http://jsfiddle.net/yvecai/7e8tksm3/
My code works as follow: each time I display something in Mydiv, I clone it and append it in an array.
The function prev() or next() append the corresponding nodes from the array for display.
The script first create 5 contents '1' ... '5' that the user can display with the functions prev() and next(). In IE, when you go prev(), then next(), only the first and last records are shown. In other browsers, no problem.
var cache = [];
var i = 0;
function next() {
var hist = document.getElementById('history');
i += 1;
if (i > 4) {
i = 4
};
hist.innerHTML = '';
hist.appendChild(cache[i]);
}
function prev() {
var hist = document.getElementById('history');
i -= 1;
if (i < 0) {
i = 0
};
hist.innerHTML = '';
hist.appendChild(cache[i]);
}
function cacheInHistory(div) {
cache.push(div.cloneNode(true));
}
function populate() {
for (i = 0; i < 5; i++) {
var hist = document.getElementById('history');
hist.innerHTML = '';
var Mydiv = document.createElement('div');
Mydiv.innerHTML = i;
hist.appendChild(Mydiv);
cacheInHistory(Mydiv);
}
i = 4
}
I tried to simplify your code:
In the function populate (onload) create and populate the array cache. As last operation append your child.
In your next or previous function use replaceChild instead of append and remove innerHTML.
var cache=[];
var i = 0;
function next(){
var hist = document.getElementById('history');
i = (++i > 4) ? 4 : i;
hist.replaceChild(cache[i], hist.children[0]);
}
function prev(){
var hist = document.getElementById('history');
i = (--i < 0) ? 0 : i;
hist.replaceChild(cache[i], hist.children[0]);
}
function cacheInHistory(div){
cache.push(div.cloneNode(true));
}
function populate(){
var hist = document.getElementById('history');
for (i=0 ; i<5 ; i++){
hist.innerHTML='';
var Mydiv = document.createElement('div');
Mydiv.innerHTML = i;
cacheInHistory(Mydiv);
}
i = 4
hist.appendChild(cache[i]);
}
<body onload="populate();">
<div id="prev" onclick="prev()">
prev
</div>
<div id="next" onclick="next()">
next
</div>
<hr/>
<div id="history">
</div>
</body>

Outputting a random image from an array using JS

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>

Continuously loop through JavaScript text array onclick

I have a text array. I want to display the first entry on page load. And then replace the text with the next entry when I click a button. If I keep clicking the button I want the text to continuously be replaced by waht is next in the array, and when it gets to the end start back at the first entry. Can someone please show me an example code for that. I am new to this.
Here's what I have
$(document).ready(function(){
var arr = new Array("One","Two","Three");
var len=arr.length;
$('#next').click(function(){
for(var i=0; i<len; i++) {
$('#quote').html(arr[i]);
}
});
});
Something like the following should do the trick:
<script type="text/javascript">
var nextWord = (function() {
var wordArray = ['fe','fi','fo','fum'];
var count = -1;
return function() {
return wordArray[++count % wordArray.length];
}
}());
</script>
<p id="foo"> </p>
<button onclick="
document.getElementById('foo').innerHTML = nextWord();
">Update</button>
Edit
Radomised version:
var nextWord = (function() {
var wordArray = ['fe','fi','fo','fum'];
var copy;
return function() {
if (!copy || !copy.length) copy = wordArray.slice();
return copy.splice(Math.random() * copy.length | 0, 1);
}
}());
The following should do it http://jsfiddle.net/mendesjuan/9jERn/1
$(document).ready(function(){
var arr = ["One","Two","Three"];
var index = 0;
$('#next').click(function(){
$('#quote').html(arr[index]);
index = (index + 1) % arr.length ;
});
});
Your code was writing all three values each time you clicked it (but only displaying that last value)
I think something like this would work
The javascript would look like:
// assuming maxTextArrayIndex & textArray are defined & populated
var textDisplayIndex = -1;
document.getElementById('textDisplay').innerHTML = textArray[textDisplayIndex];
function nextElement()
{
textDisplayIndex += 1;
if (textDisplayIndex > maxTextArrayIndex)
{
textDisplayIndex = 0;
}
document.getElementById('textDisplay').innerHTML = textArray[textDisplayIndex];
}
The html would look like:
<body onLoad=nextElement()>
...
<elementToDisplayText id=textDisplay></elementToDisplayText>
<button onClick=nextElement()>Next</button>

Categories

Resources