How to make carousel with images? - javascript

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>

Related

trying to make randomised stats (of a RPG character) render in web browser (JavaScript)

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>

JavaScript not working for all HTML pages

I am working on the tablet's display of a Pepper robot; I have a functional HTML index page comprising a list of questions—each question redirects to its respective HTML when clicked on—, 2 volume buttons and 2 other buttons—one that pops up an instruction image and the other one that closes the index page and gets back to the splash screen, which when clicked upon, reveals the index page. So far everything is working. The issue is that when I click a question—I get redirected to its HTML page, but then I get stuck there, as neither the 2 volume buttons nor the 2 other buttons work;
I made sure to include the following in each HTML page:
<script type="text/javascript" src="/libs/qimessaging/2/qimessaging.js"></script>
<script type="text/javascript" src="faq.js"></script>
I also reused the same JavaScript functions that worked for the index page.
I commented out some line:
btnPrevious.addEventListener('click', goToPreviousPage);
because I noticed it prevented the splash screen from disappearing when clicked on—i.e., the visibility attribute stays on visible instead of switching to hidden thus revealing the index page, but still, the 3 remaining buttons don't work anyway.
Here is my faq.js code:
/* global QiSession */
var serviceName = 'ADFAQ';
var volumeUpEvent = serviceName + '/VolumeUp';
var volumeDownEvent = serviceName + '/VolumeDown';
var volumeData = serviceName + '/Volume';
/* Clickable buttons */
var btnReturn = document.getElementById('return');
var btnHelp = document.getElementById('call_help');
var btnPrevious = document.getElementById('previous_page');
var btnVolUp = document.getElementById('volume-up');
var btnVolDown = document.getElementById('volume-down');
/* Help image and splash screen */
var helper = document.getElementById('helper');
var img = document.getElementById('click_on_me');
var memory;
var volume;
var audioDevice;
QiSession(connected, disconnected);
function connected (s) {
console.log('QiSession connected');
var questions = document.getElementById('questions');
/* Associating buttons to their respective functions */
btnHelp.addEventListener('click', showHelper);
btnReturn.addEventListener('click', closeQuestions);
//btnPrevious.addEventListener('click', goToPreviousPage);
btnVolUp.addEventListener('click', raiseVolume);
btnVolDown.addEventListener('click', lowerVolume);
img.addEventListener('click', loadQuestions);
questions.addEventListener('click', clickOnQuestion);
s.service('ALMemory').then(function (m) {
m.subscriber(serviceName + '/DialogEnded').then(function (subscriber) {
subscriber.signal.connect(hideQuestions);
});
m.subscriber(serviceName + '/Pepper').then(function (subscriber) {
subscriber.signal.connect(displayPepperHTML)
});
m.subscriber(serviceName + '/RaiseVolume').then(function (subscriber) {
subscriber.signal.connect(raiseVolume);
});
m.subscriber(serviceName + '/LowerVolume').then(function (subscriber) {
subscriber.signal.connect(lowerVolume);
});
memory = m;
});
s.service('ALAudioDevice').then(function (a) {
a.getOutputVolume().then(assignVolume);
audioDevice = a
});
}
function disconnected () {
console.log('QiSession disconnected');
}
function assignVolume(value){
volume = value;
}
function raiseVolume (event) {
var changed = 0;
if(volume < 100) {
volume = Math.min(volume + 5, 100);
audioDevice.setOutputVolume(volume);
changed = 1;
}
memory.insertData(volumeData, volume);
memory.raiseEvent(volumeUpEvent, changed);
}
function lowerVolume (event) {
var changed = 0;
if(volume > 30) {
volume = Math.max(volume - 5, 0);
audioDevice.setOutputVolume(volume);
changed = 1;
}
memory.insertData(volumeData, volume);
memory.raiseEvent(volumeDownEvent, changed);
}
function showHelper (event) {
if (btnHelp.innerHTML === '?') {
helper.style.opacity = '1';
helper.style.zIndex = '1';
btnHelp.innerHTML = '←';
} else {
helper.style.opacity = '0';
helper.style.zIndex = '-1';
btnHelp.innerHTML = '?';
}
btnHelp.blur();
}
function loadQuestions (event) {
memory.raiseEvent(serviceName + '/LoadQuestions', 1);
img.style.visibility = 'hidden';
}
function goToPreviousPage () {
window.location.href = "index.html";
}
function displayPepperHTML() {
window.location.href = "pepper.html";
}
function closeQuestions (event) {
if(location.href != "index.html")
{window.location.href = "index.html";}
memory.raiseEvent(serviceName + '/CloseQuestions', 1);
btnReturn.blur();
}
function hideQuestions (data) {
if (data !== 0) {
img.style.visibility = 'visible';
helper.style.opacity = '0';
btnHelp.innerHTML = '?';
}
}
function clickOnQuestion (event) {
memory.raiseEvent(serviceName + '/' + event.target.id, 1);
}
Here is my non-functioning pepper.html code:
<!DOCTYPE html>
<html lang="fr">
<head>
<title>Pepper</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=1280, user-scalable=no" />
<link type="text/css" rel="stylesheet" href="css/style.css" />
<link type="text/css" rel="stylesheet" href="css/faq.css" />
</head>
<body>
<header>
<h1>Bla bla bla</h1>
<span class="buttons">
<button id="previous_page" class="button-help"> ← </button>
<button id="return" class="button-return">X</button>
</span>
<div id="helper" class="pop-up">
<img src="img/interactionscreen_frf.png" alt="Bla bla bla">
</div>
</header>
<ul id="questions">
<p>
Bla bla bla
</p>
<div class="volume-part">
<div id="volume-up" class="Click-me">+</div>
<img src="img/speaker.png" alt="Bla bla bla" style="vertical-align: middle;">
<div id="volume-down" class="Click-me">-</div>
</div>
</ul>
<script type="text/javascript" src="/libs/qimessaging/2/qimessaging.js"></script>
<script type="text/javascript" src="faq.js"></script>
</body>
</html>
Thank you for your help.
I am expecting the pepper.html page to respond to both the volume and ← and X buttons, as the index.html should, since they use the exact same Javascript.
I was able to find some workaround: creating one JavaScript file for each HTML page, this is redundant and non-optimal I know, but at least it works.
This also made me realize that the commented-out line was blocking the program because the index.html page doesn't use the previous_page button, that's what led me to make a JS file for each HTML page.
If anybody has any other suggestions I am all ears.
Edit: I reduced the number of JS scripts to only 2. One for the index.html and the other for the identically-structured html pages of the other questions.

Automatically load next image from array everytime user enters website

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

How to make multiple random images appear upon clicking another using Javascript?

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

switch from image to random image onclick with JavaScript

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>

Categories

Resources