views:

79

answers:

3

Is it possible to use a string from an elements CSS class as an array name?
I'm looking for a smarter way of storing default animations that may grow over time to include more options in the array.

Example


JavaScript (jQuery): -

var a1 = ['red', 'pink']; 
var a2 = ['green', 'lime']; 
var a3 = ['blue', 'cyan']; 

$('ul li').click(function() { 
    arr = $(this).attr('class');    // Does this need to be converted?
    $('div#sprite').css('background', arr[0]);    // Is this kosher?
    $('div#sprite p').css('color', arr[1]); 
    });  

HTML: -

<div id='sprite'><p>Lorem ipsum...</p></div>

<ul>
    <li class='a1'>Array 1</li>
    <li class='a1'>Array 2</li>
    <li class='a1'>Array 3</li>
    </ul>

Thanks in advanced!

+2  A: 

You should use jQuery's meta-data plugin. It allows you to store any element-related data in class or any data-* attribute.

Eimantas
+1 for writing it before me, so I don't have to edit it into my answer.
Kobi
This will likely help now I've come round to your/Kobi's thinking. Thanks Eimantas!
LeslieOA
+2  A: 

You can access a global (top-level) variable by name using:

window[arr]

So you're looking for window[arr][0]. See it in action here: http://jsbin.com/ofemo

However, this creates close linkage between your JavaScript and design. I usually prefer to use .addClass, and define the colors using CSS.

Kobi
Thanks Kobi, that demo really helped; it **was** a case of variable scope :-|. You're right about using classes; I'll be using jQuery color transitions between sections/pages.Now I'm thinking about it creating an 'array' from my stylesheets section colours (<body class='red'>) would make a lot more sense. Grr; SO is a gift and a curse. Thanks again!
LeslieOA
+2  A: 

Alternatively, have an array like this:

var colors = {
    'a1':{
        'background-color':'red',
        'color':'pink'
    },
    'a2':{
        'background-color':'green',
        'color':'lime'
    },
    'a3':{
        'background-color':'blue',
        'color':'cyan'
    }
}

and then

$('div#sprite').css(colors[$(this).attr('class')]);
Eric
Probably not going to stick with arrays, but thanks for the tip, didn't know they could be declared like this. Peace Eric.
LeslieOA
To clarify: this is technically an object, not an array. Notice how each value has a corresponding key. Javascript allows you to access properties via `[]` notation which makes it look like an array.
Joel Potter
Isn't it both an associative array and an object? In Javascript, they are one and the same.
Eric