Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript variable to call object function [duplicate]

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 ?

like image 779
davewoodhall Avatar asked Aug 24 '26 00:08

davewoodhall


1 Answers

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");
like image 113
Rajaprabhu Aravindasamy Avatar answered Aug 26 '26 15:08

Rajaprabhu Aravindasamy



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!