3

I'm new to OOP, so please excuse me if my terminology is off. I'm trying to use a function parameter to call an object argument.

I think this would be more understandable with sample code:

JS

$(".color").click(function()
{
    var newColor = $(this).attr("data-color");
    functions.colors.show(newColor);
});

var functions =
{
    colors:
    {
        show: function(newColor)
        {
            $("h1").text(myTexts.test.newColor);
        }
    }
} // end functions

var myTexts =
{
    test:
    {
        red: "Bright red",
        green: "Grassy green",
        blue: "Sky blue"
    }
} // end texts

As you can see, I'm trying to get, say, "Sky blue", to show up inside my h1. However, when I click, say, to show "Bright red", this is not working.

As reference, here is my HTML:

HTML

<span class="color" data-color="red">Red</span>
<span class="color" data-color="green">Green</span>
<span class="color" data-color="blue">Blue</span>

From my understanding, when I click a color, I my color (data-color attribute) is parsed into the "show()" function, but I can't get the proper text to show up.

Why is that ?

davewoodhall
  • 998
  • 3
  • 18
  • 43

1 Answers1

3

Try to use bracket notation at this context,

$("h1").text(myTexts.test[newColor]);

Full code,

var functions =
{
    colors:
    {
        show: function(newColor)
        {
            $("h1").text(myTexts.test[newColor]);
        }
    }
} 

And as well as you should use .data(key) while fetching a data attribute..

var newColor = $(this).data("color");
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130