Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use current elements class as an array name?

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!

like image 724
LeslieOA Avatar asked Dec 03 '25 03:12

LeslieOA


2 Answers

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.

like image 130
Kobi Avatar answered Dec 04 '25 15:12

Kobi


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

like image 34
Eimantas Avatar answered Dec 04 '25 15:12

Eimantas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!