I'm currently trying to make an image that upon clicking, disappears and shows three random images. So far I thought maybe duplicating the clickable image twice and just making those invisible would work, so they would change to one of the random images and become visible after clicking the image. If you have any other idea of how this may work, I'd really like to know!
Also does anyone know how I could make it so that an image could only be used for one of the three spots, so that you always have three different random images next to each other.
Here is my JS and HTML:
var playerImg;
var playerImg2;
var playerImg3;
var playerArray = ["A1.png", "A2.png", "A3.png", "A4.png", "A5.png", "M1.png", "M2.png", "M3.png", "M4.png", "M5.png", "V1.png", "V2.png", "V3.png", "V4.png", "V5.png", "D1.png", "D2.png", "D3.png"];
function openPack() {
var randomPlayer = (Math.floor(Math.random() * 18) + 1);
playerImg = playerArray[randomPlayer - 1];
document.getElementById("pack").src = "image/" + playerImg;
var randomPlayer2 = (Math.floor(Math.random() * 18) + 1);
playerImg2 = playerArray[randomPlayer2 - 1];
document.getElementById("player2").src = "image/" + playerImg2;
var randomPlayer3 = (Math.floor(Math.random() * 18) + 1);
playerImg3 = playerArray[randomPlayer3 - 1];
document.getElementById("player3").src = "image/" + playerImg3;
}
document.querySelectorAll("img#player2")[0].addEventListener("click", openPack);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<img id="pack" src="image/pack.png" alt="Unopened pack">
<img id="player2" src="image/pack.png" alt="Place for a second player after the pack is opened">
<img id="player3" src="image/pack.png" alt="Place for a third player after the pack is opened">
<img id="veld" src="image/veld.png" alt="Football field with positions">
</body>
<script src="scripts/packs.js"></script>
</html>
Let me know if I forgot to tell something, and thank you!
Here new openPack function that will exclude duplicates
function openPack() {
var playerArraycopy = playerArray.slice();//getting new copy of initial input
function getRandomImg(){
return playerArraycopy.splice([Math.floor(Math.random() * playerArraycopy.length)],1)[0];//calculating a new random image and removing it from copy to exclude duplicates
}
document.getElementById("player2").src = "image/" + getRandomImg();
document.getElementById("pack").src = "image/" + getRandomImg();
document.getElementById("player3").src = "image/" + getRandomImg();
}
check Array.splice for more information
Related
Total JavaScript noob here. I am coding a character creation system in JavaScript. My problem is that I cannot get my randomised stats render in browser. I can get them render in console though. I have my .HTML file linked with my .JS file. I tried to find a answer to this but could not find it. Thank you.
const stats = ['Vitality','Strength', 'Agility', 'Dexterity', 'Wisdom', 'Charisma', ]
stats.forEach(function (item, index) {
console.log(item, Math.floor(Math.random() * 10) + 1)
})
I'm hoping this is the solution you're looking for.
Click the button "Run code snippet" to see it in action.
<html>
<head>
<title>Random Stats</title>
</head>
<body>
<h1>Stats</h1>
<div id="stats"></div>
<!-- NOTICE THIS AT THE BOTTOM OF THE BODY TAG -->
<!-- This is so it can load the page and find the dom element -->
<script type="text/javascript">
// 1. Create Your List
const stats = ['Vitality','Strength', 'Agility', 'Dexterity', 'Wisdom', 'Charisma'];
// 2. Choose the dom element you want to add to
const statsElement = document.querySelector('#stats');
// 3. Append stats for each to dom element
stats.forEach(function (item, index) {
// Notice the += to add to what already exists
statsElement.innerHTML += item + ":" + (Math.floor(Math.random() * 10) + 1) + "<br />";
});
</script>
</body>
</html>
Use "Run code snippet" to see how it looks like
const stats = ['Vitality','Strength', 'Agility', ];
const statsValues = {};
// Generate object what contains your values { 'Vitality': 4, 'Strength': 5 etc}
for (let i = 0; i < stats.length; i += 1) {
const nameStat = stats[i];
statsValues[nameStat] = Math.floor(Math.random() * 10) + 1;
}
// apply them to HTML
for (let i = 0; i < stats.length; i += 1) {
const nameStat = stats[i];
document.querySelector(`#${nameStat}`).innerHTML = `${nameStat}: ${statsValues[nameStat]}`;
}
// You can do it in one for, or in forEach if you like
<html>
<head>
<title>Random Stats</title>
</head>
<body>
<h1>Stats</h1>
<div id="Vitality"></div>
<div id="Strength"></div>
<div id="Agility"></div>
</body>
</html>
For a larger project in a web design class, I have to create a carousel that moves between images every ten seconds.
We did an example in class that worked with changing between 10 different words, but I can't seem to add in the pictures and have it work.
I was just wondering if someone could help me out with this part of the assignment I can't seem to grasp.
Here's what I have so far:
<head>
<title>JS Examples: Arrays</title>
<script>
function showImages(id) {
var images = ['img1', 'img2', 'img3', 'img4', 'img5', 'img6', 'img7', 'img8', 'img9', 'img10'];
document.getElementById('image').innerHTML = images[id];
console.log('Position:' + id + ' image:' + images[id]);
if (id < images.length - 1) {
id = id + 1;
} else {
id = 0;
}
setTimeout(showImages, 10000, id);
}
</script>
</head>
<body onload="showImages(0)">
<article>
<p id="image">Showing Images</p>
</article>
</body>
I'm making a image carousel to get some more experience.
I have an acf gallery in the back-end where i add my images.
This is the code that i use here:
<div class="images">
<img id="carousel_images_top" src="" alt="">
<div class="top_button next">Next</div>
<div class="top_button prev">Prev</div>
</div>
<script>
var imageList = [];
<?php
$images = get_field('image_carousel');
foreach($images as $img) {
echo "imageList.push('" . $img['url'] . "');";
}
?>
var imageTag = document.querySelector('#carousel_images_top');
imageTag.src = imageList[0];
function next() {
console.log(imageTag.src)
var curIndex = imageList.indexOf(imageTag.src);
imageTag.src = imageList[(curIndex+1) % imageList.length];
};
function prev() {
console.log(imageTag.src)
var curIndex = imageList.indexOf(imageTag.src);
imageTag.src = imageList[(curIndex-1 + imageList.length) % imageList.length];
};
document.querySelector('.next').addEventListener('click', next);
document.querySelector('.prev').addEventListener('click', prev);
</script>
I can see the first image in the array, and i can go back one to see the last one, but I can't go more than one back, and then forward to the first one again.
I do not get any errors at all, and I have tried to find out where the error is, but in the array, all of my 6 images is listed and the buttons are working.
I'm guessing there is an error in the curIndex variable, but I can't realy see what.
Anyone that can have a quick look and point me in the right direction?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Static Template</title>
</head>
<body>
<div class="images">
<img id="carousel_images_top" src="" alt="">
<p>Current Index: <span id="currentindex"></span></p>
<div class="top_button next">Next</div>
<div class="top_button prev">Prev</div>
</div>
<script>
var imageList = [
'https://tse1-mm.cn.bing.net/th?id=OIP.2bdrFgmVuK6LO0ggJdNPZAHaFP&w=152&h=105&c=8&rs=1&qlt=90&dpr=1.5&pid=3.1&rm=2',
'https://tse1-mm.cn.bing.net/th?id=OIP.yP3sLQkAOswh1wDZq21NtwHaFj&w=144&h=105&c=8&rs=1&qlt=90&dpr=1.5&pid=3.1&rm=2',
'https://tse1-mm.cn.bing.net/th?id=OIP.FEUTSwbKW9ndBYzd-oI8OQHaIN&w=99&h=105&c=8&rs=1&qlt=90&dpr=1.5&pid=3.1&rm=2',
];
var imageTag = document.querySelector('#carousel_images_top');
var currentindexTag = document.getElementById('currentindex');
imageTag.src = imageList[0];
function next() {
//console.log(imageTag.src)
var curIndex = imageList.indexOf(imageTag.src);
imageTag.src = imageList[(curIndex+1) % imageList.length];
currentindexTag.innerHTML = curIndex;
};
function prev() {
//console.log(imageTag.src)
var curIndex = imageList.indexOf(imageTag.src);
imageTag.src = imageList[(curIndex-1 + imageList.length) % imageList.length];
currentindexTag.innerHTML = curIndex;
};
document.querySelector('.next').addEventListener('click', next);
document.querySelector('.prev').addEventListener('click', prev);
</script>
</body>
</html>
Follow the code you write, the images replacement does work correctly except the input of images array has same url.
Because the indexOf method returns the first index at which a given element can be found in the array, or -1 if it is not present.
var images = ['1.png', '1.png', '1.png'];
//no matter how many times to execute images.indexOf('1.png'), it's always return 0.
So, the better solution is that replacing of the curIndex with a global number, like below:
var curIndex = 0;
function prev() {
...
curIndex -= 1
}
function next() {
...
curIndex += 1;
}
This solution should be avoiding the problem you meet.
That's an example and it makes some evidences for the correct of your script.
There are two directions to find the problem is. One, to check the images input, and another, try to debug the code in reality environment.
So this code selects random image whenever a person loads my website, how can I change the code so that images are selected sequentially from first to last everytime a person loads the website and then again resets to first image when the counter reaches the end?
P.s- The code works fine on hosting server, here it gives an error i don't know why.
window.onload = choosePic;
var myPix = new Array("https://i.imgur.com/LHtVLbh.jpg", "https://i.imgur.com/2YHazkp.png", "https://i.imgur.com/Uscmgqx.jpg");
function choosePic() {
var randomNum = Math.floor(Math.random() * myPix.length);
document.getElementById("myPicture").src = myPix[randomNum];
}
<!DOCTYPE html>
<html>
<head>
<title>Random Image</title>
<script src="thumb.js"></script>
</head>
<body>
<img src="images/spacer.gif" id="myPicture" alt="some image">
</body>
</html>
You can use localstorage to achieve this. When the user enters the website, you can do something like:
var pictureIndex = localstorage.getItem("pictureIndex");
But since it may be the user's first visit, it would be better to have:
var pictureIndex = localstorage.getItem("pictureIndex") || 0;
Then, you just increment the pictureIndex and perform a modulo operation (for the case when this is the last image)
pictureIndex = (pictureIndex + 1) % myPix.length;
To save this index, you can use
localStorage.setItem('pictureIndex', pictureIndex);
Next time when the user refreshes the page (or comes back), he will get the next picture in your array.
The final code should look like this:
window.onload = choosePic;
var myPix = new Array("https://i.imgur.com/LHtVLbh.jpg", "https://i.imgur.com/2YHazkp.png", "https://i.imgur.com/Uscmgqx.jpg");
function choosePic() {
var pictureIndex = window.localStorage.getItem("pictureIndex") || 0;
pictureIndex = (pictureIndex + 1) % myPix.length;
window.localStorage.setItem("pictureIndex", pictureIndex);
document.getElementById("imgid").innerHTML = pictureIndex;
document.getElementById("myPicture").src = myPix[pictureIndex];
}
<!DOCTYPE html>
<html>
<head>
<title>Random Image</title>
<script src="thumb.js"></script>
</head>
<body>
Press "Run" multiple times to cycle through the images.
Currently showing: <span id="imgid"></span>
<img src="images/spacer.gif" id="myPicture" alt="some image">
</body>
</html>
Note that the above code might not work here (but you can test it locally) due to some security restrictions from jsfiddle. A working version can be accessed >here<
function choosePic() {
var local_item = 0;
if(localStorage.getItem('pic_key')){
local_item = parseInt(intvlocalStorage.getItem('pic_key'));
}
if(local_item >= myPix.length){
local_item = 0;
}
localStorage.setItem('pic_key', local_item + 1);
document.getElementById("myPicture").src = myPix[local_item];
}
You can use LocalStorage to achieve this. When the user enters the website, you can store the key and increment it.
Use local storage to save the data you need [e.g. visited = 3(3rd time the same person visited your website)]
Your js code can be implemented like this:
window.onload = choosePic;
var myPix = new Array("https://i.imgur.com/LHtVLbh.jpg", "https://i.imgur.com/2YHazkp.png", "https://i.imgur.com/Uscmgqx.jpg");
function choosePic() {
if (localStorage.getItem('visited') == null)
{
document.getElementById("myPicture").src = myPix[0];
localStorage.setItem('visited', 1);
}
else if (localStorage.getItem('visited') >= myPix.length)
{
localStorage.setItem('visited', 0);
document.getElementById("myPicture").src = myPix[localStorage.getItem('visited')];
}
else
{
document.getElementById("myPicture").src = myPix[localStorage.getItem('visited')];
localStorage.setItem('visited', localStorage.getItem('visited') + 1);
}
}
I'm trying to build something that would resemble a slide show, where you have an image and when you click on it, it is replaced by another randomly in my series of images. I first tried with simple html, but of course the images don't switch randomly. So I did my research and found that it could be done with an array in Javascript. I just don't really know a lot about javascript…
This is what I could find but it doesn't work, I'm sure there is a stupid mistake in there that I can't see:
this is my javascript
function pickimg2() {
var imagenumber = 2 ;
var randomnumber = Math.random();
var rand1 = Math.round((imagenumber-1) * randomnumber) + 1;
myImages1 = new Array();
myImages1[1] = "img_01.gif";
myImages1[2] = "img_02.gif";
myImages1[3] = "img_03.gif";
myImages1[4] = "img_04.gif";
myImages1[5] = "img_05.gif";
myImages1[6] = "img_06.gif";
myImages1[7] = "img_07.gif";
myImages1[8] = "img_08.gif";
myImages1[9] = "img_09.gif";
var image = images[rand1];
document.randimg.src = "myImages1";
}
there is my html
<!DOCTYPE html>
<html>
<head>
<title>mur</title>
<link rel="stylesheet" href="style.css">
<link rel="JavaScript" href="script.js">
</head>
<body onLoad="pickimg2">
<div class="fenetre">
<img src="img_01.gif" name="randimg" border=0>
</div>
</body>
</html>
If someone has another solution I'm open to it!
Fix your script link like RamenChef mentioned:
<script type="text/javascript" src="script.js"></script>
Here's the updated code, check console.log to see the different image urls getting requested.
var myImages1 = new Array();
myImages1.push("img_01.gif");
myImages1.push("img_02.gif");
myImages1.push("img_03.gif");
myImages1.push("img_04.gif");
myImages1.push("img_05.gif");
myImages1.push("img_06.gif");
myImages1.push("img_07.gif");
myImages1.push("img_08.gif");
myImages1.push("img_09.gif");
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function pickimg2() {
document.randimg.src = myImages1[getRandomInt(0, myImages1.length - 1)];
}
<div class="fenetre">
<a href="#" onClick="pickimg2();return false;">
<img src="img_01.gif" name="randimg" border=0>
</a>
</div>
this code bellow is working. I hope it's what you were asking for
var images = [
"http://img1.science-et-vie.com/var/scienceetvie/storage/images/galerie/deepsea-challenge-le-film-de-james-cameron-livre-des-images-inedites-des-grands-fonds-marins-5165/19818-1-fre-FR/Deepsea-challenge-le-film-de-James-Cameron-livre-des-images-inedites-des-grands-fonds-marins_square500x500.jpg",
"http://static.mensup.fr/photos/145240/carre-premieres-images-officielles-pour-assassin-s-creed-rogue.jpg",
"http://www.pnas.org/site/misc/images/16-01910.500.jpg" ];
init();
function random_image(images) {
var random = randomize(images);
while(images[random] === document.getElementById("image").src){
random = randomize(images)
}
document.getElementById("image").src = images[random].toString();
}
function randomize(array){
return Math.floor((Math.random() * (array.length)));
}
function init() {
document.getElementById("image").addEventListener("click", function(){
random_image(images);
});
random_image(images);
}
<!DOCTYPE html>
<html>
<head>
<title>Bonjour</title>
</head>
<body >
<div class="fenetre">
<img id="image" src="" name="randimg" >
</div>
</body>
</html>