Automatically load next image from array everytime user enters website - javascript

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

Related

How do you save a state in HTML?

As you might know from my previous posts, I am developing a chrome extension. I have a button that toggles the extension on & off, and this button's state is saved when you click out of the extension. You can see the code for this below:
popup.html
<!DOCTYPE html>
<html>
<head>
<link rel="StyleSheet" type="text/css" href="style_popup.css"/>
<script type="text/javascript" src="popup.js"></script>
</head>
<body>
<div class="navbar">
View My Dashboard
</div>
<h1 class="center">[Title]</h1>
<button id="buttonclick" class="button">Enable Control</button>
<br> <img src="green_circle.PNG" height="140" width="150" id="centerimage"> <br>
<p class="center" id="status"> [Title] is running! </p>
</body>
</html>
popup.js
let changeColor = document.getElementById('changeColor');
chrome.storage.sync.get('color', function(data) {
changeColor.style.backgroundColor = data.color;
changeColor.setAttribute('value', data.color);
});
document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('buttonclick');
// onClick's logic below:
link.addEventListener('click', function() {
handler();
});
});
function handler()
{
chrome.storage.local.get({count: 0}, function (result) {
var count = result.count;
var buttonState = document.getElementById('buttonclick');
var imageState = document.getElementById('centerimage');
var status = document.getElementById('status');
if (count == 0) {
buttonState.style.backgroundColor = "#75ad0a";
buttonState.innerHTML = "Enabled";
imageState.src = "green_circle.PNG";
status.innerHTML = "[Title] is running!"
count = 1;
}
else {
buttonState.style.backgroundColor = "#AA2B0E";
buttonState.innerHTML = "Disabled";
imageState.src = "red_circle.png";
status.innerHTML = "[Title] is not running!"
count = 0;
}
chrome.storage.local.set({count: count});
});
}
However, I am running into a bit of a pickle. I want to make it such that if a user were to click the button (thereby disabling the extension), exit the chrome extension, and then click back into it, it would still show as disabled. With my current case, however, it will just display the "Enable Control" and "[Title] is running" every time they open the extension UNTIL the user clicks the button. In other words, it would be reset & and I want the state to be preserved. As you can see from my popup.js, I've already written code that saves the state of a variable, but I am unsure how to actually make the state be preserved in the HTML. I would greatly appreciate any help, thanks!

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.

Jackhammers not changing on mouseover

I'm trying to get the image to change based on one second timer, but the image stays one the first object in the array
the code I have so far is
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Lab 8 - Jackhammer Man</title>
<script type="text/javascript">
var jackhammers = new Array();
jackhammers[0] = "<img src='Images/jackhammer0.gif'>";
jackhammers[1] = "<img src='Images/jackhammer1.gif'>";
jackhammers[2] = "<img src='Images/jackhammer2.gif'>";
jackhammers[3] = "<img src='Images/jackhammer2.gif'>";
jackhammers[4] = "<img src='Images/jackhammer4.gif'>";
jackhammers[5] = "<img src='Images/jackhammer5.gif'>";
jackhammers[6] = "<img src='Images/jackhammer6.gif'>";
jackhammers[7] = "<img src='Images/jackhammer7.gif'>";
jackhammers[8] = "<img src='Images/jackhammer8.gif'>";
jackhammers[9] = "<img src='Images/jackhammer9.gif'>";
jackhammers[10] = "<img src='Images/jackhammer10.gif'>";
var curJackhammer;
function bounce() {
var img = document.getElementsByTagName("img");
var i = 0 ;
for (i = 0; i<10;i++) {
if(jackhammers[i].src == img.src) {
if(i === jackkhammers.length) {
img.src = jackhammers[0].src;
break;
}
img.src = jackhammers[i+1].src;
break;
}
}
}
</script>
</head>
<body>
<img onMouseOver="setInterval(function(){bounce},1000);" onMouseOut="clearInternval(fuction(){bounce};" src="Images/jackhammer0.gif" id="hammer" name="hammerman" alt="Jackhammer Man">
</body>
</html>
The issue I'm coming across is the mouseover event will not activate, I am having trouble finding the error in my code as the debuggers I have aren't finding any. Any help trying to get the mouseover function of the image changing ever so often would be appreciated.
you have a typo if(i === jackkhammers.length)
jackhammers[x] has no src property so to get its value use it without .src
instead of
onMouseOver="setInterval(function(){bounce},1000);"
write:
onMouseOver="setInterval(function(){bounce();},1000);"
var img = document.getElementsByTagName("img");
This returns a NodeList, or an array of elements. You need to access the index of this element with [0]
Or better yet, use querySelector which returns the first element in a NodeList
You keep referring to the src property of items in the jackhammers array:
img.src = jackhammers[0].src;
even though items in that array are strings, not objects.
Also, there's a typo here:
if(i === jackkhammers.length) {
These kinds of errors would be immediately visible the with dev tools of your browser of choise. Put a breakpoint to where you suspect things go wrong and start investigating variables and your assumptions while stepping through the code.
See here: http://www.creativebloq.com/javascript/javascript-debugging-beginners-3122820
Updated code changed a few things around based on some advice from my mentor.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Lab 8 - Jackhammer Man</title>
<script type="text/javascript">
var jackhammers = new Array(11);
jackhammers[0] = "Images/jackhammer0.gif";
jackhammers[1] = "Images/jackhammer1.gif";
jackhammers[2] = "Images/jackhammer2.gif";
jackhammers[3] = "Images/jackhammer3.gif";
jackhammers[4] = "Images/jackhammer4.gif";
jackhammers[5] = "Images/jackhammer5.gif";
jackhammers[6] = "Images/jackhammer6.gif";
jackhammers[7] = "Images/jackhammer7.gif";
jackhammers[8] = "Images/jackhammer8.gif";
jackhammers[9] = "Images/jackhammer9.gif";
jackhammers[10] = "Images/jackhammer10.gif";
var curJackhammer = 0;
var direction;
var begin;
function bounce(){
if(curJackhammer == 10)
curJackhammer = 0;
else
++curJackhammer;
document.getElementsByTagName("img")[0].src = jackhammers[curJackhammer].src;
if(curJackhammer == 0)
direction = "up";
else if(curJackhammer == 10)
direction = "down";
document.getElementsByTagName("img")[0].src = jackhammers[curJackhammer];
}
function startBouncing(){
if (begin)
clearInterval (begin);
begin = setInterval("bounce()",90);
}
</script>
</head>
<body>
<h1>Jackhammer Man</h1>
<p><img onMouseOver="startBouncing();" onMouseOut="clearInterval(begin);" src="Images/jackhammer0.gif" height="113" width="100" alt="Image of a man with a jackhammer." /></p>
</body>
</html>
>
Used firebug to step into code, works once I set into it but simply putting a mouse over nothing happens.

javascript dice game - image does not change

Having a slight issue calling a math.random image for a dice game. When I click the roll button the image does not change. I have the images saved where the .html file is. Any help is much appreciated!
Roll The Dice
<script type="text/javascript">
var dieImage;
function start()
{
var button = document.getElementById(rollButton);
button.addEventListener("click", rollDice, false);
dieImage = document.getElementById("die1");
}
function rollDice()
{
setImage(dieImage);
}
function setImage(dieImg)
{
var dieValue = Math.floor(1 + Math.random() * 6);
dieImg.setAttribute("src", "die" + dieValue + ".jpg");
dieImg.setAttribute("alt", "dieImg with" + dieValue + "spots");
if (dieValue == 6)
{
document.getElementById("sometext").innerHTML = "You Win!";
}
else
{
document.getElementById("sometext").innerHTML = "Roll Again";
}
}
window.addEventListener("load", start, false);
</script>
</head>
<body>
<form action = "#">
<input id = "rollButton" type = "button" value = "Roll Dice">
</form>
<li>
<img id = "die1" src = "die1.jpg" alt = "blankImage">
</li>
<div id = "sometext">Roll for a 6!</div>
</body>
The only issue with the code above is this line:
var button = document.getElementById(rollButton);
Should read
var button = document.getElementById("rollButton");
The above change DOES cause the function to work, and the image to be updated. Assuming all of your images are in fact in the right place, you will see them change.
As a note of encouragement, I would suggest you code in Firefox, and get Firebug. With these tools, you can then utilize the Firebug console and/or Firefox's Web Developer Error Console. These are tremendously useful for troubleshooting problems like this quickly.

Categories

Resources