bboybeatle
bboybeatle

Reputation: 567

Use a class name to call variable of the same name

I have a list of divs with the class "dot" as well as a a different class on each for a town name, (eg. london, glasgow etc.)

I'm trying to use the second class name as a variable in a function. If I echo the second class name into the function it reads it as just a string as opposed to the variable which represents a number...

var resize = function () {
    $('.dot').each(function () {
        uniName = $(this).attr('class').split(' ')[1];
        uniNameMargin = uniName / 2 - uniName;
        $('.' + uniName).animate({
            width: uniName,
            height: uniName,
            marginLeft: uniNameMargin,
            marginBottom: uniNameMargin
        }, 300);
    });

Currently this formula is trying to use the words as a number and returning a lot of NaNs as opposed to the number

Is there any way of making it read it as the related variable instead?

Thanks

Upvotes: 1

Views: 294

Answers (1)

Paul D. Waite
Paul D. Waite

Reputation: 98796

You don’t show us where these variables are defined, but I assume they’re global variables. If so, they’re also properties of the global object, which in web browsers is the window property.

If you have an object’s property name as a string, you can access that property using square bracket notation:

var my_object;
my_object.london = 1;

var property_name = "london";
console.log( my_object[property_name] ); // Will log 1 to the console

So, you can access the value of your variables like this (as I said, assuming they’re global variables):

    uniName = $(this).attr('class').split(' ')[1]; // After this line, I’m assuming uniName has a value like "london"
    var uniNumber = window[uniName];
    uniNameMargin = uniNumber / 2 - uniNumber; // Here, we use [] notation to access the "london" property of the window object. If you have a global variable called "london" with a numerical value, this should now work.

I also notice that the variables in your $('.dot').each function aren’t declared within the function using var. If those variables have already been declared in a higher scope, cool, but if they’re only used in that function, you should declare them in that function using the var keyword, so that you don’t pollute the parent or global scope with variables you don’t need:

$('.dot').each(function () {
    var uniName = $(this).attr('class').split(' ')[1];

    var uniNumber = window[uniName];

    var uniNameMargin = uniNumber / 2 - uniNumber;

    $('.' + uniName).animate({
        width: uniName,
        height: uniName,
        marginLeft: uniNameMargin,
        marginBottom: uniNameMargin
    }, 300);
});

Upvotes: 3

Related Questions