Displaying images with Javascript based on user input - javascript

I have been trying to display image with the following code. The user input is intended to be compared to bring up the right picture.
$(document).ready(function(){
var defaultimg = document.getElementById('image1');
defaultimg.src = pictureImage;
var pictureImage = "images/unknown.png";
if({{messages.get.message}} == "Mewtwo"){
var imgobject = document.getElementById('image1');
imgobject.src = pictureImage;
pictureImage = "images/150.png";
}
if({{messages.get.message}} == "Charmeleon"){
var imgobject2 = document.getElementById('image1');
imgobject2.src = pictureImage;
pictureImage = "images/005.png";
}
if({{messages.get.message}} == "Warturtle"){
var imgobject3 = document.getElementById('image1');
imgobject3.src = pictureImage;
pictureImage = "images/008.png";
}
)}
to the following piece of html
<img id="image1" alt="Pokemon" width="88" height="75"> 
At the moment it only displays an empty box.
Can someone offer advice on whether this approach can be fixed to display the images? Thanks for the time and help.

that's probably a reference loop:
$(document).ready(function(){
var defaultimg = document.getElementById('image1');
// defaultimg now contains image1
// using jQuery and getElementbyId together is weired
defaultimg.src = pictureImage;
// pictureImage is not assigned, so the url is empty
// prob. cause for empty block?
var pictureImage = "images/unknown.png";
// ok, now we assign an url
if({{messages.get.message}} == "Mewtwo"){
// is that path correct?
var imgobject = document.getElementById('image1');
// copy of the empty image from above
imgobject.src = pictureImage;
// we assign an url
pictureImage = "images/150.png";
// new url on pictureImage, unused so far.
}
...
if none of the conditions like if({{messages.get.message}} == "Mewtwo"){
is true, it must show nothing due to defaultimg.src = pictureImage; with unassigned pictureImage variable.

You might want to state with which kind of template engine or the like you work, as "{{messages.get.message}}" wouldn't help you much in vanilla js (though it would be syntactically well formed)
Tip for debugging:
debugger;
in js code starts up the debugger in chrome/firefox(+firebug)/...
otherwise you can also use the console commands, e.g.
console.debug("if 1")
to find out what is happening
also have a look at console output in general, there should be no warnings or errors.
Next:
You're trying to use the probably global (because of missing "var" in front) variable "pictureImage" before you define it. Javascript is run from start to end, from left to right (let's just assume it's that way for easier understanding), top to bottom.
So you try to set the src of an image to something which is undefined at that point, and later on define that variable. There is no such thing as pointers to non-object types in javascript (which string constants are)
To fix your problem you'll probably have to swap some lines in your code, so the used variable gets set, and THEN is used, not the other way around.

Related

Having a number at the end of a file and increasing it by 1 each time (with Javascript)?

My JS file creates this image and adds it to a folder.
'writenewimage_'+objId+'.png';
Currently 'writenewimage_'+objId+'.png' just keeps getting replaced/overwritten, which isn't ideal. objId is "1".
What I'd like is for that number "1" at the end of the image name to increase by 1. So that each time the code is executed it adds a different new image to the folder. 'writenewimage_1','writenewimage_2','writenewimage_3' etc.
Would super appreciate any help! I'm a newbie to Javascript and this would be very helpful to learn. :)
Here is the code that includes this file:
Echomap_LoaderCCG.prototype.processDataToGame = function (gameActor, dataActor) {
Echomap.Utils.log('processDataToGame', 'Called');
//Echomap.Params.CCGData = {};
var faPath = Echomap.CCGUtil.getFacesPath();
var tvPath = Echomap.CCGUtil.getTVPath();
var svPath = Echomap.CCGUtil.getSVPath();
var objId = Echomap.Utils.getActorIdFromActor(gameActor);
var objName = gameActor._name;
Echomap.Utils.log('processDataToGame','objId', objId);
Echomap.Utils.log('processDataToGame','objName', objName);
gameActor.isComposite = undefined;
gameActor.composite = {};
gameActor.composite.filename = {};
gameActor.composite.filename.face = faPath + 'writenewimage_'+objId+'.png';
gameActor.composite.filename.tv = tvPath + 'writenewimage_'+objId+'.png';
gameActor.composite.filename.sv = svPath + 'writenewimage_'+objId+'.png';
If it's confusing or you need more code than this, let me know! There might be some more I need to show, I'm not sure, but I don't wanna overwhelm you all with anything that might be irrelevant. I'm a bit of a noob with JS and trying to get my head around it. Just wanna try and increase "writenewimage_1"s number by 1 each time so they can be separate files if possible rather than have it keep overwriting the same file. ^_^

Accessing an object within an object for jquery/underscore.js

Can't believe this has proven so difficult.
I have the following JSON:
{"1440071374-Bane breathing.jpg":{"filename":"1440071374-Bane
breathing.jpg","alt":"This is bane","primary":true,"caption":"This is
Banecat, the worst enemy of Batcat"}}
I've converted this into an object with the following underscore syntax:
_.each(results, function(r) {
var obj = JSON.parse(r.images)
Pseudo for what I want to do is as follows:
if primary exists and is true {
var img = filename
I'd have thought it was an obvious job of just obj[0].filename but apparently not and I've been stuck on this for awhile now.
Any help is greatly appreciated.
I've come back to the problem after the weekend and I'm noticing the JSON is not being treated as an object:
<%
_.each(results, function(r) {
var a = r.images;
_.isObject(a); // strangely now resulting in false????
_.isString(a); // true
When I echo the JSON onto the page using the underscore syntax <%= r.images %> I get the json I've pasted at the top of this question. Perhaps because the results are coming from a request it needs to be parsed first?
Your JSON is already a object (dictionary). All you need to do is iterate and validate whether primary is true and if it is, assign filename value to var img
var a = {"1440071374-Bane breathing.jpg":{"filename":"1440071374-Bane breathing.jpg","alt":"This is bane","primary":true,"caption":"This is Banecat, the worst enemy of Batcat"}};
for (items in a) {
if (a[items]['primary'] == true) {
var img = a[items]['filename'];
alert(img); // <-- will display 1440071374-Bane breathing.jpg in this example
}
}
Same code in JSFiddle. Play around with different values.
Why don't add src dynamically? Add the following code and it should work. Make sure that you have an <img> element with an unique id
document.getElementById('imgId').src = "example.com/" + img;
I have also edited the code in the same fiddle as above.

Need ExtendScript to open a file without knowing the full file name

New to ExtendScript and trying to finish an automation project for work.
I have a bunch of images that I am combining in photoshop via a script and need to open a image pairing based on an initial image. I know that the name of my paired file will be predictable up until the final character, at which point it will be any uppercase letter A-Z.
For example:
CH-14B1-SP-01-A can pairs with CH-14B1-SP-PV-01-A, but could also conceivably be paired with CH-14B1-SP-PV-01-B. Each paired file has an A-D replicate and we choose the best to be paired.
I have a script working that requires user input to decide what replicate to look for. I want to automate this. My code looks like this:
// ask user input for PV replicate letter
var repLetter =prompt("Which PV replicate would you like to use? (A.. B.. C.. etc.)");
// get the info out of the source doc
var fileName = srcDoc.name;
var docName = fileName.substring(0,fileName.length -4);
var filePath = srcDoc.path.toString();
var fileExt = fileName.substring(fileName.length -4, fileName.length);
var nameCheck = fileName.substring(0,fileName.indexOf("CH-14B1-SPI-"));
if (nameCheck <1)
{
var fileNum = fileName.substring(12,fileName.length -5) + repLetter;
// no underscore so we need to open it's namesake
// alert(nameCheck)
var filePair = filePath + "/PV/" + "CH-14B1-SPI-PV-" + fileNum + fileExt;
openThisFile(filePair)
Is there any way to make the var repLetter just accept any value at all?
Something like
var fileNum = fileName.substring(12,fileName.length -5) + [a-z];
I tried the above hoping it would do the trick (again very new to this) and I was told that "a" was undefined.
Your fault lies in the incorrect syntax in
var fileNum = fileName.substring(12,fileName.length -5) + [a-z];
... it's just bad syntax, you seem to be mixing GREP into JS. The error is issued because [...] indicates an array, which is valid to 'add' to a string, but the expression a-z ("a minus z") needs variables named a and z. I suppose you simply wanted some sort of wildcard here.
Circumvent the entire issue by reading a list of candidate files, based on the current file name. This is kind of hard to test locally because it requires lots of dummy files (and I'm not entirely sure I understand your procedure). However, the general idea of the following should be clear.
Rather than prompting for 'any' letter, it's more user friendly to show the available choices. I am not sure how you get the list of candidates, so I'll let you fill in that yourself. You need to adjust the getFiles call for this; currently, it reads the files from filePath, with a * after its name to pick up everything starting with nameCheck.
The found list of files is shown in a simple dialog with radio buttons to pick a file from. As it is, it only shows an alert, and if you press Cancel it does nothing.
Please note I have tested this inside InDesign, not Photoshop, as it's an easier test bed for scripts, and so it is possible some of the property names are off.
srcDoc = app.activeDocument;
var fileName = srcDoc.name;
var docName = fileName.substring(0,fileName.lastIndexOf('.'));
var filePath = srcDoc.filePath.toString();
var fileExt = fileName.substring(fileName.lastIndexOf('.')+1);
var nameCheck = fileName.substring(0,fileName.indexOf("CH-14B1-SPI-"));
var filelist = Folder(filePath).getFiles (nameCheck+'*.'+fileExt).sort();
if (filelist.length == 0)
{
alert ('No files found matching '+nameCheck+'*.'+fileExt);
} else
{
var fileDialog = app.dialogs.add({name:"Choose a file", canCancel:true});
with (fileDialog)
{
with(dialogColumns.add())
{
with (fileSel = radiobuttonGroups.add())
{
radiobuttonControls.add({staticLabel:filelist[i].name,checkedState:i==0});
}
}
}
if (fileDialog.show() == true)
{
alert ('you picked '+filelist[fileSel.selectedButton].name);
}
}

Pass in vars to an eval workaround to process a code string from a json object after YUI compression

I need to pass a jQuery object in to a workaround for an eval. The issue is that i need access to a jQuery object that is out side the eval area but i can't see to pass it in. here is what i have.
var jObj = $(selector);
var myCode = "var jObj="+jObj+"; var i="+i+"; "+shape.mouseover.onEnd.replace("\u0027","'");
var myFucn = new Function(myCode);
myFucn();
the oject I'm getting the string out of is
shape.mouseover.onEnd.replace("\u0027","'");
is working and what I'm passing in that string is
open_info(jObj,i)
Which is what i have to fire. The deal is that the code is run thru YUI compressor so the jObj var becomes something else so i need to pass that in. Right now i get an error where it thinks it should have and ending ] which is not right. I is working it seems, just not the jObj var.
EDIT
there are many way to get where i need to be that are close but not quite like
How to pass parameters in eval in an object form?
shape.mouseover.onEnd = "open_info(jObj,i)";
/*
* this is coming in and must be as it is, don't say it's wrong please
* it's not able to be done anyother way!
*/
//lets process the string and pull in the vars
/* BEOFRE YUI COMPRESSOR CHANGES THINGS and works!!!
var jObj = $(selector);
var i = 1;
var myCode = shape.style.events.mouseover.onEnd.replace("\u0027","'");
var myFucn = new Function(myCode);
myFucn();
*/
// AFTER note it can be random as i change code so it fails cause
// var jObj is now var r and var i is now var e
var r = $(selector);
var e = 1;
var p= shape.style.events.mouseover.onEnd.replace("\u0027","'");
var f= new Function(p);
f();
Now it works before the compression.. After is not due to the change. Hope tha tclears it up some
I might be going down the wrong tracks and be confused here..
But isnt this what your trying to do?
Send myFucn the correct object and what ever i is
myFucn($(selector),10);
function myFucn(jObj,i)
{
shape.mouseover.onEnd.replace("\u0027","'");
}
I still don't understand why this question got 2 down votes, but well it's solved and works great. The trick is to do the same manipulation of the dom state. It's really simple once it is placed out.
//so this is what the object is parsed out to from the json string
//since you can't just pass a function stright that way any how
shape.mouseover.onEnd = "open_info(jObj,i)";
//this is what will take that string and process it
//note jObj is what is in the orgain code but it changes to
// var r or something else that is shorter after going thru YUI compressor
// Which is why we can't just use open_info(jObj,i) and it work..
// ie: it's not an issue with scoope but an issues with var names being shortened
(function(){
//this is the trick on passing them so YUI doesn't get them
//use a string and YUI skips it so we directly create the
//needed oject in the window namespace
window['jObj']=jObj; window['i']=i;
var p= shape.mouseover.onEnd;
var f= new Function(p);
f();
})();
That is it.. I put it in a click or hover event so it's kin to an onClick.
/* EXMAPLE OUTPUT AFTER YUI COMPRESSION
//Note after the YUI compressor get ahold of that
//processing code above it'll look like
*/
function(){window.jObj=n,window.i=t;var u=i.mouseover.onEnd,r=new Function(u);r()}();
So the way that works is, I needed to fix the issue of the var jObj being renamed. So I simply made a sting for the name and let the compressed the var name fill the name of the object I need for the processed code string. Don’t know why I didn’t see it before and I would have saved my rep value :-\ .. oh well. May be a way to shorten this but I'm leaving it for now.
Edit
I recant the edit it was working. :) Very well.. Left wondering what any other ways there would be to make it do the same thing.

JQuery: image src variable clean up

I've been teaching myself how to use jquery the past few days, haven't used it much, i'm kinda still stuck in old ways (back 10 yrs ago lol) To get started i downloaded the JQuery Desktop from JQuery Desktop - Nathan Smith, to keep from repetitive use of image src links inevatibly making the file larger than what it needs to be. So while making the reference variables basically started to use the same stuff over again... i tried looking up to see how to compress it or clean it up some but kept running into dead ends for what i am trying to do... if anyone happens to know what i could do that would be awesome.
Code
enter code here
/* SAVES DATA SPACE ALSO CREATES QUICK REFFERENCE/VARIABLE */
var healthVar= 'assets/img/icons/health.png';
var emailVar = 'assets/img/icons/email.png';
var linkVar = 'assets/img/icons/link.png';
var noteVar = 'assets/img/icons/note2.png';
var videoVar = 'assets/img/icons/video1.png';
var xxxVar = 'assets/img/icons/xxx.png';
var socialVar = 'assets/img/icons/social.png';
var webdesktopVar = 'assets/img/icons/webdesktop.png';
var androidVar = 'assets/img/icons/android.png';
var devVar = 'assets/img/icons/development.png';
var secureVar = 'assets/img/icons/secure.png';
var signalVar = 'assets/img/icons/signal.png';
var setVar = 'assets/img/icons/settings.png';
var spamVar = 'assets/img/icons/spam.png';
var feedbackVar = 'assets/img/icons/feedback.png';
$("#health_Pic").attr("src", healthVar);$("#health_PicB").attr("src", healthVar);$("#health_PicC").attr("src", healthVar);
$("#email_Pic").attr("src", emailVar);$("#email_PicB").attr("src", emailVar);$("#email_PicC").attr("src", emailVar);
$("#link_Pic").attr("src", linkVar);$("#link_PicB").attr("src", linkVar);$("#link_PicC").attr("src", linkVar);
$("#note_Pic").attr("src", noteVar);$("#note_PicB").attr("src", noteVar);$("#note_PicC").attr("src", noteVar);
$("#video_Pic").attr("src", videoVar);$("#video_PicB").attr("src", videoVar);$("#video_PicC").attr("src", videoVar);
$("#social_Pic").attr("src",socialVar);$("#social_PicB").attr("src", socialVar);$("#social_PicC").attr("src", socialVar);
$("#webdesktop_Pic").attr("src",webdesktopVar);$("#webdesktop_PicB").attr("src",webdesktopVar);$("#webdesktop_PicC").attr("src",webdesktopVar);
$("#android_Pic").attr("src",androidVar);$("#android_PicB").attr("src",androidVar);$("#android_PicC").attr("src",androidVar);
$("#dev_Pic").attr("src",devVar);$("#dev_PicB").attr("src",devVar);$("#dev_PicC").attr("src",devVar);
$("#secure_Pic").attr("src",secureVar);$("#secure_PicB").attr("src", secureVar);$("#secure_PicC").attr("src", secureVar);
$("#signal_Pic").attr("src", signalVar);$("#signal_PicB").attr("src", signalVar);$("#signal_PicC").attr("src", signalVar);
$("#settings_Pic").attr("src", setVar);$("#settings_PicB").attr("src", setVar);$("#settings_PicC").attr("src", setVar);
$("#spam_Pic").attr("src",spamVar);$("#spam_PicB").attr("src", spamVar);$("#spam_PicC").attr("src", spamVar);
$("#feedback_Pic").attr("src", feedbackVar);$("#feedback_PicB").attr("src", feedbackVar);$("#feedback_PicC").attr("src", feedbackVar)
I have tried to do this:
$("#health_Pic","#health_PicB","#health_PicC").attr("src", healthVar);
With no luck, thanks for any info a head of time
Try:
$("#health_Pic,#health_PicB,#health_PicC").attr("src", healthVar);
The jQuery attr function takes only the first element obtained by the selector.
Get the value of an attribute for the
first element in the set of matched elements.
Use a loop to change multiple images src.
EDIT: After checking the docs and trying it myself, I found that using the .attr as a setter does set the value for all elements. Thanks j08691 for pointing this out.

Categories

Resources