Turn a string into a variable name using window (JavaScript) - javascript

After scouring the forums, I've been trying to use window to turn a parameter entered as a string into a workable variable. Here we start with the target location in the p tag...
<p id="rent"></p>
Then I call the function using the parameter "rent" to obtain the variable rent.
var rent = 125;
function display(attribute) {
document.getElementById(attribute).innerHTML = window.attribute;
}
display("rent");
However it still returns "undefined" so I must be making a mistake in syntax. Any solutions?
Update: #Sidd has the right approach in changing it to window[attribute] but I still can't get it to work with object properties, for example if you call rent.amt.

You almost have it:
var rent = 125;
function display(attribute) {
document.getElementById(attribute).innerHTML = window[attribute];
}
display("rent");
window.attribute looks for a variable called attribute instead.

Related

Animate CC - Call instance with var Strings

I'm trying to make a function that make play a symbol animation (hijo) when i click other one (padre). I want a function to use them many times so I'm trying to automatized.
Im getting the instance name of click button "padre" and try to add some sting after that in this case "hijo". I created some vars but when i use string value it doesn't work.
this.padre.addEventListener("click", nose.bind(this));
function nose(evt) {
var root = this
//In this case on evt.currentTarget.name i get 'padre'
var loprimero = evt.currentTarget.name;
var loquesigue = "hijo";
var todito = loprimero + loquesigue;
//This console fine the name of instance i want gotoAndPlay
console.log(todito);
//This is i want to make work
//This give me cannot read property 'gotoAndPlay' of undefined
root.todito.gotoAndPlay(1);
//And this work fine
this.padrehijo.gotoAndPlay(1);
}
When I define var loquesigue = this.padrehijo; without quotation marks it works fine. But remember I need to use this on some other parents symbols.
This is simply logging a string:
console.log(todito);
If you have an instance with that name, you can access it using brackets:
var inst = root[todito];
console.log(inst); // Does this work?
One other note, you don't need to use bind in EaselJS, you can just use on() and its a little cleaner (docs) :)
this.padre.on("click", nose, this);
Cheers,

Is it possible when we define an object to set an attribute with the value of another attribute of itself?

I would like when I'm creating an object in Js to be able to define an attribut including the value of a previous attribut of the same object (therefore not to repeat element if I want to define an attribut with a part of an other attribut), but I don't know if it's possible.
I show you my code:
var Sel = {
timSand: document.getElementById('tim-sand'),
timSandHei: getComputedStyle(timSand).height, // not Working
}
var Sel = {
timSand: document.getElementById('tim-sand'),
timSandHei: getComputedStyle(document.getElementById('tim-sand')).height, // Working but a bit dirty
}
So when I'm doing the first exemple, I have an error, and I have to replace timSand in the second line by document.getElementById('tim-sand'), like on the second exemple.
Do you know a way to avoid this ?
You cannot because the object does not exist yet, so you cannot reference it.
But you can use a variable to avoid the heavy DOM access.
var sand = document.getElementById('tim-sand')
var Sel = {
timSand: sand,
timSandHei: getComputedStyle(sand).height, //Working
}

Accessing values in javascript

I am using a JS library for facetracking/emotion detection called CLMtracker.
http://auduno.github.io/clmtrackr/examples/clm_emotiondetection.html
Note: Seems to work best in chrome for those trying to use it.
Is the example I am using, I am wondering how I can access the values for each emotion. For instance, I want check every 10 seconds what the values are and print to console. From this I would also like to compare the values to find the highest and find the emotion that is attached to that. I think I am right in saying that the max() function will give me the highest out of an array?
What I have tried:
I have tried to get emotionData[0].emotion and emotionData[0].value which should print Angry and the value, but it only prints 0. I have also tried the same method with data which does not seem to return anything.
EDIT
emotionData gets me:
however it does not seem to show any update/change as I make my expression change
ec.meanPredict(ctrack.getCurrentParameters()) returns an object containing all the current scores for all emotions.
To get the current score of "Angry", for example, you would do :
ec.meanPredict(ctrack.getCurrentParameters())[0].value
So, in order to get the current most probable emotion, you could do this :
function getCurrentEmotion()
{
if(!ec.meanPredict(ctrack.getCurrentParameters())){setTimeout(getCurrentEmotion,1000);return;}
var currentData = ec.meanPredict(ctrack.getCurrentParameters());
var currentScores = [];
//Gather all scores in an array
for(var i=0;i<currentData.length;i++)
{
currentScores.push(currentData[i].value);
}
//Get the biggest score
var max = Math.max.apply(null,currentScores);
//Calculate its index
var indexOfScore = currentScores.indexOf(max);
//Get the associated emotion
var emotion = currentData[indexOfScore].emotion;
console.log(emotion);
//Set up a loop (did not add 'var', to allow stopping it from outside)
currentEmotionLoop = setTimeout(getCurrentEmotion,3000);
}
To stop the loop at any time, do this :
clearTimeout(currentEmotionLoop);
By the way, the ec variable is declared privately, so in order for this to work, either remove var where it is declared :
var ec = new emotionClassifier();
or write this code in the same file, under the same scope.

Trying to reduce repetition of javascript using a variable

I am trying to reduce the repetition in my code but not having any luck. I reduced the code down to its simplest functionality to try and get it to work.
The idea is to take the last two letters of an id name, as those letters are the same as a previously declared variable and use it to refer to the old variable.
I used the alert to test whether I was getting the right output and the alert window pops up saying "E1". So I am not really sure why it wont work when I try and use it.
E1 = new Audio('audio/E1.ogg');
$('#noteE1').click(function() {
var fileName = this.id.slice(4);
//alert(fileName); used to test output
fileName.play();
$('#note' + fileName).addClass('active');
});
The code block works when I use the original variable E1 instead of fileName. I want to use fileName because I am hoping to have this function work for multiple elements on click, instead of having it repeated for each element.
How can I make this work? What am I missing?
Thanks.
fileName is still a string. JavaScript does not know that you want to use the variable with the same name. You are calling the play() method on a string, which of course does not exist (hence you get an error).
Suggestion:
Store your objects in a table:
var files = {
E1: new Audio('audio/E1.ogg')
};
$('#noteE1').click(function() {
var fileName = this.id.slice(4);
//alert(fileName); used to test output
files[fileName].play();
$('#note' + fileName).addClass('active');
});
Another suggestion:
Instead of using the ID to hold information about the file, consider using HTML5 data attributes:
<div id="#note" data-filename="E1">Something</div>
Then you can get the name with:
var filename = $('#note').data('filename');
This makes your code more flexible. You are not dependent on giving the elements an ID in a specific format.

Accessing Variables in Javascript using .length

I'm pretty new to Javascript, so forgive me if this is a simple question.
I'm trying to access the length of a set of checkboxes in a form using Javascript. However, I need to be able to change the "name" field of the checkboxes to check several different sets of them. Right now, my sample code looks like:
var set = "set" + x;
totalLength = optionBoxes.set.length;
The variable x is being incremented by a for loop that wraps the whole thing and the name of the checkbox sets that I'm trying to access are set0, set1, set2, etc.
Thanks.
Edit: small typo fixes
Probably you want this:
var set = "set" + x;
totalLength = optionBoxes[set].length;
In Javascript, properties of an object are usually accessed as object.name, but they can also be accessed by object["name"] if you have the name as a string.
if you think that your code should otherwise work try:
totalLength = optionBoxes[set].length;

Categories