The CatAPI - Multiple Random Images for Javascript Object - javascript

The CatAPI is an API which will send you a random GIF of a cat each time you access it.
The Cat API
It works like it is supposed to. The issue is....I am using this in Google Maps. I have many icons that show up on the screen, when you load the icon, it will load the event properties ("Name, blah etc") into the info window. I have also given it a Cat Attribute which is the link to a random GIF (You may see where this is headed already)
The random cat gif ends up being the same gif for every InfoWindow (Even though the data is changing for each).
[EDIT] I should clarify, the "data" that is changing is the City Name, Location...not the url for the Cat gif
How do I resolve this random url http://thecatapi.com/api/images/get?format=src&type=gif to equal a specific image and apply that to my icons "cat" attribute.
Javascript Object getting cat attribute
if (results.list.length > 0) {
resetData();
for (var i = 0; i < results.list.length; i++) {
results.list[i].imacat = "http://thecatapi.com/api/images/get?format=src&type=gif"
geoJSON.features.push(jsonToGeoJson(results.list[i]));
}
drawIcons(geoJSON);
}

Well...it turns out I was making it harder in my head than I ever needed to....let this be a lesson to everyone.
Simple creating a timestamp variable at the end of the url allowed me to create an original request which the catapi could just dump off.
Example:
var ts = new Date().getTime();
results.list[i].imacat = "http://thecatapi.com/api/images/get?format=src&type=gif&timestamp="+ts;
This creates something random on the end and I will get a bunch of objects with unique cat gifs!

Related

how to set an image using a url from a data set on code.org

i have a program that takes info from a data set about birds and it will show a random bird and its info based on a random number that's generated I have everything down except the image part
I tried using
setImageURL("birdInfoImage",birdImage[index]);
in a function but an error appeared saying "setImageURL() url parameter value (undefined) is not a string"
Edit: this is for a homework assignment on code.org. The picture should be taken from the data set in the site in the "image of bird" column
var birdImage = getColumn("100 Birds of the World", "Image of Bird");
then I used bird image in a function to use the URL of the image in the data set and set that URL as the image
onEvent("initiateButton","click",function(){
var index = getNumber("randomNumberOutput");
setText("birdInfoName", reducedBirdList[index]);
setText("birdInfoScientificName", reducedBirdList[index]);
setText("birdInfoColor", PrimaryColor[index]);
setText("birdInfoDiet", birdDiet[index]);
setImageURL("birdInfoImage",birdImage[index]);
hope that helped

Photoshop Script to Randomly Select Images

I am trying to use Javascript to select two random images from a local folder and place on separate Photoshop layers. I have created an array with the filepaths to choose from.
#target photoshop
var allImages = [“file path/img-1.jpg”, "file path/img-2.jpg", "file path/img-3.jpg"];
//this is a large array of file paths to 100 different images
var pickImage = allImages[Math.floor(Math.random() *
allImages.length)];
var imgFile = File(pickImage);
var openFile = app.open(imgFile);
var secondImage = allImages[Math.floor(Math.random() * allImages.length)];
app.activeDocument.artLayers.add(secondImage);
This opens the first image and creates a blank layer above but does not insert the second image. What am I missing?
In javascript, you must first create a file object before you may open an image. All you have to do is create the variable and then point it at secondImage. Just like you did with the first image:
var imgFile = File(pickImage);
In your current approach, your easiest solution would probably be to just make a variable secondPickedImage and assign it to the same thing as pickImage. Although, this leaves the possibility of you picking the same image, you could fix that with an if statement.
I would recommend changing your approach and turning pickImage into a function that you can call that will return a random number for your array - saves space, and cleans up your code. Then put the secondImage assignment in a do while loop that keeps picking a random number until you pick a number different from the pickImage number so your first and second pictures are different.
Source: http://wwwimages.adobe.com/www.adobe.com/content/dam/acom/en/devnet/photoshop/pdfs/photoshop-cc-scripting-guide.pdf page 29.

How do i link all this images with an array

How do i link all this images to an array, so as this links can work when i click each image slide
jQuery(document).ready(function() {
var bgImageArray = ["banner1.jpg", "banner2.jpg", "banner3.jpg"],
var links = ['http://google.com', 'http://hotmail.com', 'http://yahoo.com', 'http://kimjoyfox.com'],
base = window.location.origin + "/wp-content/themes/fbnquest/img/home/",
secs = 4;
bgImageArray.forEach(function(img){
new Image().src = base + img;
// caches images, avoiding white flash between background replacements
});
The way I understand your problem is the following :
For each time you click on one of each of the images, you want to redirect the user to one of the URLs, changing the URL each time the user click on the image.
Is it what you want ? If not, please can you precise your problem
[EDIT]
So yes,
Here is my way of solving your problem, If you don't matter, I won't give you code, obviously, you do this for training, let's do it :
Create an eventListener on click that will trigger a function called ChangeImageUrl (for example) and assign that eventListener to all the img elements
Then create a function that will detect the current URL of the image clicked, using imgElement.src ( i advice you to devide the src string using split or equivalent, that way you can directly access by index the current url )
Once you have the URL Use yourUrlArray.indexOf(currentImageSrcUrl), to catch the index of the current URL in your array, store it and increment it ( bonus if the increment value is upper than the URL array length, set it to 0 )
access the new src using yourUrlArray[newindex]
assign current img element the new src that we juste have extracted
Tell me if this answer is good for you, I hope it will
I was trying to understand what do you really want and I did something that I hope help you.
Inside of the loop you can do in this way below.
var i = new Image();
i.src = base + img;

Store a changing jQuery variable to session or local storage

I currently have the following jQuery code working. Here's what it does: when I click a button, it will swap between classes. Each of those classes contains a background image. So, as I click this single button, it cycles through the background images. (edit: I just need to store whatever the current variable is, so when they swap pages, that variable is what's loaded).
$('.button').mousedown(function () {
$('#backgrounds').each(function(){
var classes = ['bg1','bg2','bg3','bg4'];
this.className = classes[($.inArray(this.className, classes)+1)%classes.length];
});
});
However, my website has multiple pages. So, what I need to do is store the current variable to the session storage or local storage, and then retrieve that variable on page load. That way as I jump from one page to another, the same class (and therefore background image) will be displayed. I don't need to (nor want to) use cookies -- I just need this to last the current session.
Additionally, if possible (though much less important than storing the variable), I'd also like this jQuery function to neatly fade when swapping from one background image to another. Right now it "snaps" from one image to the next as it swaps out the classes.
Thanks in advance -- any help greatly appreciated!
Use the Window.sessionStorage API for a single session.
Just set by getting the value from the sessionStorage if applicable (if not, set a default value):
var classes = sessionStorage.getItem(classes) || ['bg1','bg2','bg3','bg4'];
and set it when you need to:
sessionStorage.setItem("classes", classes);
The selector #backgrounds should only match one element. So it is unnecessary to use each:
// Define classes & background element.
var classes = ['bg1','bg2','bg3','bg4'],
$bg = document.getElementById('backgrounds');
// On first run:
$bg.className = sessionStorage.getItem('currentClass') || classes[0];
// On button click:
$('.button').mousedown(function () {
// (1) Get current class of background element,
// find its index in "classes" Array.
var currentClassIndex = classes.indexOf($bg.className);
// (2) Get new class from list.
var nextClass = classes[(currentClassIndex + 1)%classes.length];
// (3) Assign new class to background element.
$bg.className = nextClass;
// (4) Save new class in sessionStorage.
sessionStorage.setItem('currentClass', nextClass);
});
In this demo I've used getElementById to select the #backgrounds DOM element, rather than selecting it using jQuery. This is because jQuery element representations don't actually have a className property, and the ordinary JavaScript API is simpler in this case.

why are variables not showing up as members of objects?

hey guys i'm working on some code for a class project and for some reason the demo code i got in class is not working the same way. the errors aren't making any since can i get some help debugging i know its probably retarded. thanks a lot in advance.
function BuildGrid()
{
//begin with a BeginVertical() call so that controls
//are stacked vertically
GUILayout.BeginVertical();
GUILayout.FlexibleSpace();
//begin loopping for the rows
for(var i=0; i<rows; i++)
{
//call BeginHorizontal() so that controls are stacked
//horizontally
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
//begin looping for the columns
for(var j=0; j<cols; j++)
{
//getting the card object that resides
//at this location in the array
var card:Object = aGrid[i][j];
//the definition for the backside (visible part for the card
var img : String;
//check if the card is face up, if so, show the robot part
//if not show the wrench
if(card.ifFaceUp)
{
img = card.img;
}
else
{
img = "wrench";
}
//create a button using a picture instead of
//text. Getting the picture from the Resources
if(GUILayout.Button(Resources.Load(img),
GUILayout.Width(cardW)))
{
flipCardFaceUp(card);
//print to the debug the name of the picture
Debug.Log(card.img);
}
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
}
GUILayout.FlexibleSpace();
GUILayout.EndVertical();
}//end buildGrid
Class where ifFaceUP and img are defined
class Card extends System.Object
{
//is the card face up
var ifFaceUp:boolean = false;
//has the card been matched
var ifMatched:boolean = false;
//image for the card
var img: String;
//constructor
function Card(img : String)
{
this.img = img;
}
}
errors: http://puu.sh/2clHw
Looking at the script you emailed I can see that aGrid contains Objects of type Card. In ECMA JavaScript nothing is strongly typed. ECMA is the JS that runs in the browser. Your JS is .net code that runs on the server when the browser requests a certain page or used as a desktop application (not sure what type of app it is). Even though it's called JavaScript it only means that the syntax looks like JavaScript but since it's .net code it's completely different from JavaScript (ECMA).
One thing you can do with ECMA JS is:
var notStronglyTyped=22; // is int
notStronglyTyped = "hello";// changed to string
notStronglyTyped.subString();// can call subString now because it's a method of string
This will not work in .net since .net is strongly typed (and class based but that's not the problem at hand). Hence the int when you declare a variable:
var i:int=0;// the :int gives a syntax error in ECMA JS since it doesn't exist.
Strongly typed means that the variable needs to be declared or converted to a certain type before you execute functions or access properties that are accociated with that type. substring is a method of String but I can't call it on an int:
var i:int=0;
i.subString();//won't work in .net unless you cast it to another type.
((String)i).subString();//might work but I don't know the exact syntax for .net JS.
In short; when retrieving cards from aGrid I would suggest declaring them as Card since you don't need to type cast later when you declare it as Object. The array aGrid contains objects of type Card anyway so you should not get a warning or error there:
card = new Card("robot" + (i+1) + "Missing" + theMissingPart);
//instance card is of type Card
aCards.Add(card);//aCards contains items of type Card
....
aGrid[i][j] = aCards[somNum];
//aGrid is filled with items from aCards which in turn contains items of type Card
At some point in your code you do:
var card:Object = aGrid[i][j];
I am not sure why since aGrid contains Card type (everything is type Object because everything inherits from Object). So why not declare the variable card as an instance of Card?
var card:Card = aGrid[i][j];
That should solve your problem right there. I can't run the code here because I have not set up a .net develop environment but I'm sure that solves it.
You can look up articles on google on type casting (wikipedia) you can imagine the headaches that come with it when you fill an array or list with mixed types. This is where generics can lend a helping hand but it might be too early to get into that as it can make your head explode :-)

Categories