VictorVH
VictorVH

Reputation: 327

Javascript, Jquery problems with variables

I'm having a problem using variables with Jquery, and i just can't figure out what the problem is. In this instance i am trying to insert a random class to my li. When i tried alerting color i can cleary see that it writes .green or .red. Following that logic i should be able to use the variable to add my class right? But it is not working. What am i doing wrong?

(function(){

        $('li').on('click', function(){
            var number = Math.floor(Math.random() * 2);
            var colorA = ['.green', '.red'];
            var color = colorA[number];

            $(this).addClass(color);
        });
    })();

Upvotes: 2

Views: 61

Answers (2)

PKeidel
PKeidel

Reputation: 2589

Remove the Dot at the class names beginning ;-)

Upvotes: 1

Nasser Torabzade
Nasser Torabzade

Reputation: 6700

simply replace colorA with this:

var colorA = ['green', 'red'];

jQuery addClass() function accepts a class "name" not a class "selector".

Upvotes: 1

Related Questions