switch from image to random image onclick with JavaScript - 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>

Related

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

French Quiz Not Working

I have made a french quiz but it is not working.
Here is the code:
<html>
<head>
<title>Quiz</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Quiz</h1>
<p id="one"></p>
<input id="aone" />
<br>
Mark It
<script>
var verbs = ["accompagner","aider","aimer","apporter","chanter","danser","coûter","écouter","étudier","fermer","jouer","laver","marcher","montrer","oublier","passer","penser","préparer","raconter","agir","bâtir","choisir","désobéir","finir","guérir","nourrir","obéir","punir","réfléchir","remplir","réussir","rougir","saisir","attendre","défendre","descendre","entendre","interrompre","perdre","rendre","répondre","rompre","vendre"];
var verb = verbs[Math.floor(Math.random() * verbs.length)];
if(verb.slice(-2) == "er") {
var newverb = verb.substring(0, verb.length - 2);
newverb += "es";
}
if(verb.slice(-2) == "ir") {
var newverb = verb.substring(0, verb.length - 2);
newverb += "is";
}
if(verb.slice(-2) == "re") {
var newverb = verb.substring(0, verb.length - 2);
newverb += "s";
}
document.getElementById("one").innerHTML = verb;
document.getElementById("btn").onclick = function () {
if (document.getElementById("aone").value==newverb) { // Not Working.
alert("Correct");
}
}
</script>
</body>
</html>
I think I have traced the problem to the final if statement not being true but I don't understand why.
All help will be appreciated.
Its really unclear what you are trying to do since it is in another language.
However, your conditional is working. I added a alert() so you can see what "newverb" is equal to.
If in the input field, you add the value that was alerted, the conditional will work.
see fiddle: https://jsfiddle.net/DIRTY_SMITH/q7k2ez2L/

javascript code working in jsfiddle but not working in the browser [duplicate]

This question already has answers here:
JSFiddle code not working in my own page
(3 answers)
Closed 8 years ago.
my code is working in jsfiddle but not working in the browser i dont know what i missed here could you please check it and tell me the solution. i google it but i am not getting correct solution please help me
this is jsfiddle link http://jsfiddle.net/pLTrJ/9/
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"> </script>
</head>
<script type="text/javascript">
var random = 0;
var theDiv = document.getElementById("showVal");
updateTheDiv(9,0);
function updateTheDiv(inRange, inMin) {
random = (Math.random()*inRange+inMin)|0;
theDiv.innerHTML = random;
var nextCall = (Math.random()*1000)|0;
setTimeout(function() {
updateTheDiv(inRange, inMin);
}, nextCall);
}
</script>
<body>
<div id="showVal"></div>
</body>
</html>
jsfiddle has wrapped it automatically in the onload event. You haven't done this in your HTML page, so when it runs in the browser you're trying to get hold of the div before it's been rendered, so theDiv is null.
The below should work:
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"> </script>
</head>
<script type="text/javascript">
window.onload = function () {
var random = 0;
var theDiv = document.getElementById("showVal");
updateTheDiv(9, 0);
function updateTheDiv(inRange, inMin) {
random = (Math.random() * inRange + inMin) | 0;
theDiv.innerHTML = random;
var nextCall = (Math.random() * 1000) | 0;
setTimeout(function () {
updateTheDiv(inRange, inMin);
}, nextCall);
}
}
</script>
<body>
<div id="showVal">
</div>
</body>
</html>
Try this in your Browser ;)
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"> </script>
</head>
<body>
<div id="showVal"></div>
</body>
<script type="text/javascript">
var random = 0;
var theDiv = document.getElementById("showVal");
updateTheDiv(9,0);
function updateTheDiv(inRange, inMin) {
random = (Math.random()*inRange+inMin)|0;
theDiv.innerHTML = random;
var nextCall = (Math.random()*1000)|0;
setTimeout(function() {
updateTheDiv(inRange, inMin);
}, nextCall);
}
</script>
</html>
(I just put the script to the bottom. So the script loads after your element is set.)

Categories

Resources