Accessing Images from an array? - javascript

I need to create a function where the user can access input question , and they can see different results. It's a magic eight ball simulation. I need to use an array, but i'm not sure how to do this with images.
Here's what I have now.
function eightBall() {
var answer = document.getElementById('questBox').value;
answer = answer.toLowerCase();
if (answer.search(/[?]/) > -1) {
var no = '../images/eightBallNo.png';
$('#answerImages').html(no);
}
}
I'm not sure how to do this, so any help would be appreciated. In addition, I need to make it so that when the user enters the same question, it always returns the same result. My instructions were to do this through an if statement. Again, any help would be greatly appreciated.

Create a map using an object and store each question and the resulting random mage in it. When somebody asks a question, check to see if you've already mapped that question to something. If so, use the cached result. If not, get a random image from your array, and then add it to the cache:
// empty cache to use
var answerMap = {}
// array of your images
var images = ['image_1.png', 'image_2.png', ... 'image_n.png'];
function eightBall() {
var imageToUse = false;
var answer = document.getElementById('questBox').value;
answer = answer.toLowerCase();
// this syntax could be wrong, I forget the check as my JS is rusty
// check the cache to see if we got asked this before
if (answerMap[answer] != undefined) {
// if so, use the cached image value
imageToUse = answerMap[answer];
} else {
// otherwise, get a random image, and add it to the cache
var randomIndex = Math.floor(Math.random()*images.length);
imageToUse = images[randomIndex];
answerMap[answer] = imageToUse;
}
// do whatever you need to do with the image
}

Use that URL in an IMG tag, like this:
var no = '../images/eightBallNo.png';
$('#answerImages').html('<img src='+no+'/>');
But, this doesn't use an array. Where were you needing to use an Array? An Array of image urls?

Related

How to change variable values in an array of variables in JS

Not sure if this is possible to even do so I'll give it a quick shot and see if anyone has any solutions, ahem.
Is there any way I could store these variables into an array, and change them through the array as such;
function themepreviewchange() {pretaskbartxt=curcolsch[0];pretaskbartxtprs=curcolsch[1];preactivetitle=curcolsch[2];preinactivetitle=curcolsch[3];pretbgradinactive1=curcolsch[4];
pretbgradinactive2=curcolsch[5];pretbgradactive1=curcolsch[6];pretbgradactive2=curcolsch[7];cpwhite=curcolsch[8];cplightg=curcolsch[9];cpsilver=curcolsch[10];cpmidgray=curcolsch[11];
cpgray=curcolsch[12];cpblack=curcolsch[13];cpblue=curcolsch[14];cpprussian=curcolsch[15];cpwincyan=curcolsch[16];cpyellow=curcolsch[17];cpfont=curcolsch[18];cphover=curcolsch[19];
cpatext=curcolsch[20];preinvert=curcolsch[21];shuffleflop=curcolsch[22];discheckinv=curcolsch[23];enacheckinv=curcolsch[24];invcheckinv=curcolsch[25];prespritesheet=github+curcolsch[26];
cwpp=curcolsch[27]}
var settings = pretaskbartxt,pretaskbartxtprs,preactivetitle,preinactivetitle,pretbgradinactive1,pretbgradinactive2,pretbgradactive1,pretbgradactive2,cpwhite,cplightg,cpsilver,cpmidgray,
cpgray,cpblack,cpblue,cpprussian,cpwincyan,cpyellow,cpfont,cphover,cpatext,preinvert,shuffleflop,discheckinv,enacheckinv,invcheckinv,prespritesheet,cwpp,currentcolour
And just do a for loop?
for(var i=0; i<curcolsch.length; i++){settings[i]=curcolsch[i]}
The current result just ends up changing the value of that number in the array, and just changes it to the same thing as the current position in the curcolsch array. So my question is; how would I go about using a quicker route than just spamming the same set of variables with one step up in the array like I addressed above?
Just to be clear I'm not completely insane with the variable count problem, the whole reason i'm asking is so I can get rid of them.
Hoping this isn't your homework assignment....
let settings = {
pretaskbartxt: curcolsch[0],
pretaskbartxtprs: curcolsch[1],
...
cwpp: curcolsch[27],
};
for (const aThing in settings) {
console.log(`value of ${aThing} is ${settings[aThing]}`);
}
Should give you the basic idea....
I was hoping for a quick straight forward answer without the need to rewrite half my code, so I've just ended up removing all my variables in a replacement for a single array so I can switch easier and it's more compact + better than any other solution.
var preactive = [undefined,undefined,'--preactivetitle','--preinactivetitle',undefined,undefined,
undefined,undefined,'--prewhite','--prelightg','--presilver','--premidgray','--preblack',
'--preblue','--preprussian',undefined,'--preyellow','--prefont','--prehover',undefined,
'--preinvert']
function themepreviewchange() { precolsch = undefined; precolsch = schemes[themecurrent]
for(var i = 0; i<preactive.length; i++){docelem.style.setProperty(preactive[i], precolsch[i])}
gradient = "linear-gradient(90deg, " + precolsch[4] + "," + precolsch[5] + ")";

How to check presence of a URL parameter compared to an Array?

Given these two sample urls and code. How can I use the Array as a reference to check if the values are in the UTM parameter? (There will ONLY be one utm parameter at any given time).
example.com?utm=test
example.com?utm=test2
var partnerArray = ["test", 'test2'];
function findPartner() {
if window.location.href.indexOf('?utm='(partnerArray)' !== -1) {
//do something fun here
}
I know my code is wrong - I haven't found example of using an Array to check for values in the URL.
Thank you.
Let's split this into two problems. First, getting the value of the utm parameter:
function getUTM() {
return new URLSearchParams(window.location.search).get("utm");
}
Then, figuring out whether it's one of the known partners, and returning the one it might be.
const partnerArray = ["test", 'test2'];
function getPartner() {
const utm = getUTM();
return partnerArray.find(partner => partner === utm);
}
getPartner() will return undefined if the query string's utm parameter doesn't match either known partner.
Thanks all those that gave input. Here's my solution for future readers with parts from the comments.
1st: Establish an Array:
var partnerArray1 = ["test1", 'test2'];
var partnerArray2 = ["test3", 'test4'];
2nd: Check what is in the URL's UTM parameter value
var urlParams = new URLSearchParams(window.location.search).get("utm");
3rd: Make a function to check the value against the Array:
function checkUTM() {
if (partnerArray1.indexOf(urlParams) !== -1){
//do some cool stuff here
}
if (partnerArray2.indexOf(urlParams) !== -1){
//do some more cool stuff here
}
}
Short of figuring out how to pass values into the function and check that, I went with the slightly more messy way, but it accomplished my goal. If there are improvements to the above, please feel free to provide clear updated samples.

Search Alt Text, hide mismatches with jQuery / JavaScript

I am trying to implement a rudimentary site search for a page of images. The search function should go through each element in a specific class looking for a word match in the image's alt text.
I think my issue is with binding the function to a form submit but I can't seem to figure out where I went wrong.
I have tried this with jQuery (fiddle:http://jsfiddle.net/u2oewez4/)
$(document).ready(function(){
$("#search-form").click(function() {
var searchQuery = "Text";
$.each('.single-image', function(){
$(this).children("img").attr("alt"):contains(searchQuery).hide("slow");
});
});
});
As well as with JavaScript (fiddle:http://jsfiddle.net/m3LkxL1c/)
function submitSearch(){
// create regex with query
var searchQuery = new RegExp(document.getElementById('search-input').value);
// create array of content to look for query in
var content = document.getElementsByClassName("single-image");
// create an array to put the results to hide in
var hideResults = [];
var imagesToHide = document.getElementsByClassName("single-image-hide");
// get the current display value
var displaySetting = imagesToHide.style.display;
for (i=0; i<content.length; i++) {
if (! searchQuery.test(content[i].firstChild.firstChild.nodeValue)) {
// if the query not found for this result in query
hideResults.push(content[i]);
// push to the hideResults array
content[i].className = "single-image-hide";
// change class name so CSS can take care of hiding element
document.getElementById("form-success").style.display = 'inline-block';
alert(searchQuery); // for debugging
return false; // results will not stick without this?
}
}
// set display to hidden
if(displaySetting == 'inline-block'){
imagesToHide.style.display = 'none'; // map is visible, so hide it
}
else{
imagesToHide.style.display = 'inline-block'; // map is hidden so show it
}
}
FYI I have built the JQuery off a few StackOverflow threads, so I've definitely tried my best to find a similar example. (Similar functions: here, and here)
Okay, various bug fixes, most of which I noted in the comments already because I wanted to make sure not to miss any. You need to read the details for in the jQuery documentation much more closely. That'll fix a lot of the problems you're having, like using the wrong each function. Other things will come with time. Keep studying, and READ THE DOCUMENTATION.
$("#search-form").click(function() {
//this gets the val for the search box, then puts the Imgs in a variable so we don't have to use the selector multiple times. Selectors are expensive time-wise, stored variables are not.
var searchQuery = $("#search-text").val(),
singleImgs = $('.single-image');
//you have to show the images for each new iteration, or they'll remain hidden
singleImgs.show();
singleImgs.each(function(){
//get alt attribute
var thisAlt = $(this).find("img").attr("alt");
//if thisAlt does not contains searchQuery (use > instead of === for does)
if(thisAlt.indexOf(searchQuery) === -1){
$(this).hide();
}
});
});
working fiddle

Keeping a variable and string together in localstorage

Hey i want to store a piece of text plus a variable in localstorage.
This may seem a bit vague so here is what i mean with this:
var something = "text";
localStorage.setItem("localstorage", '"sometext"+something');
function functionz()
{
var displayed = localStorage.localstorage;
alert(displayed);
}
I want to make sure that displayed will display this text: sometexttext
I had it already working by storing "sometext"+something in a variable like this:
var something = "text";
localStorage.setItem("localstorage", '"sometext"+something');
function functionb()
{
var thetext = "sometext"+something;
alert(thetext);
}
The second version will give you: (sometexttext), and the first one will give you ("sometext"+something) as raw text. This is ofcourse not what i want and i wonder how i can make it so that it can be stored in localstorage and still display the second result.
Thanks in advance

Honestly hard to explain.. I use something like a=b, then a++, but b changes. Except, these are Arrays

Well my short and easy to explain explanation can be this. I have 2 arrays, FilterList and GamesReset. Whenever this function I have works and filters out some games with check boxes and a drop down menu, the function starts off with something like FilterList=GamesReset;. This functions seems to work fine until I filter out ages for the game. The function never touches GamesReset unless it's something like while(i<GamesReset.length){} or FilterList=GamesReset;. And the only tool I use when I filter games is FilterList.splice(i,1);. Now with that, GamesReset definitely, should never change as far as I know. I have it to reset FilterList, then depending on what needs to be filtered out, it will start removing those games from the FilterList. The problem I have, is that, GamesReset also becomes filtered. Which, does not make any sense at all. So like my title, it's just like saying b=0;, a=b;, a++;, and now b equals 1.
Now, I think that's the best/shortest way I can reveal this problem, without overdoing it with my bad habit of explaining things to people. I have a webpage currently available if anyone would like to see whats going on in action, because I wouldn't get what's going on with GamesReset either if I were you, here (url removed, read edit). To get the error working, just change the age to 10 without checking any boxes. The bottom paragraph is the GamesReset array (using <br> to separate each array), and it's the one that changes when I'm only changing FilterList in the JavaScript. The actual codes if you view the page source may be a little off compared to when I mentioned above, but it's pretty much 100% the same thing. I also wanted to have the codes available without a url and on this page, but I can't figure out how to do that with the html tags included.
Actually, here's the JavaScript function. I just figured out the 4 spaces thing when my question was rejected.
function SearchFilter() {
Games = GamesReset;
plat = document.getElementById('platformcheck').checked;
rpg = document.getElementById('rpgcheck').checked;
puzz = document.getElementById('puzzlecheck').checked;
hybo = document.getElementById('hybocollectcheck').checked;
ages = document.getElementById('agescheck').value;
if ((!plat) && (!rpg) && (!puzz) && (!hybo)) {
FilterList = Games;
} else {
FilterList = [];
i = 0;
while (i < Games.length) {
Set = '';
Set = Games[i];
Set = Set.split('</>');
StrFind = Set[0];
if (
(plat && (StrFind.search(',platform,') > -1)) || (rpg && (StrFind.search(',rpg,') > -1)) || (puzz && (StrFind.search(',puzzle,') > -1)) || (hybo && (StrFind.search(',hybocollect,') > -1))) {
FilterList.push(Games[i]);
}
i++;
}
// so by now, we should have the filtered array
}
//seperate filter for ages
i = 0;
while (i < FilterList.length) { //The problem should definitely start here
Set = '';
Set = FilterList[i];
Set = Set.split('</>');
StrFind = Set[1];
if ((Math.abs(StrFind)) > ages) {
FilterList.splice(i, 1);
} else {
i++;
}
}
GL.innerHTML = GamesReset.join('<br>');
}
As a reminder, the problem starts when the age filter is working. And the only thing it does is FilterList.splice(i,1);. But it ends up changing GamesReset. I changed this function a bit when I added Games=GamesReset;, but that was another test to try and make sure GamesReset doesn't get filtered like FilterList, but it still does.
EDIT: I removed my url since the answers definitely explained everything, so there's no need for it now.
Arrays are not copied when assigned, both variables will refer to the same data. Here is a post that goes into detail on this: Copying array by value in JavaScript
It makes perfect sense since variables are just references to objects in memory. One object can have several references. Consider this:
var a = { foo: 'bar' };
var b = a;
// b is now a reference to a and they both point to the same object
b.foo = 'doe';
alert( a.foo ); // alerts doe
The same goes for arrays. So when you do FilterList = GamesReset you are not copying the array - you are just assigning the same array to another variable. Any mutations or changes made to either reference will be reflected in all references.
To create a copy of an array you can use slice:
FilterList = GamesReset.slice();

Categories