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 advance!
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.
You should use jQuery's meta-data plugin. It allows you to store any element-related data in class or any data-* attribute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With