1

Its probably stupid noob general javascript question but ive been trying to find an answer for days.

Lets say i use jquery plugin that takes object as settings (i will show on flexbox called fluixbox) and i want it to take some of the settings from html.

html:

<a data-color="rgba(40,25,255,1)"> My colorful image </a>

javascript:

$("a").fluidbox({ overlayColor:   $(this).data("color") })

I think its pretty self explenatory, i tried to do everything. I think problem must be something with scope. If i just create function that returns rgba(40,25,255,1) and put it instead $(this).data("color") then it does work.

Thank you for any response.

1
  • 2
    it is scope, the use of this within the attribute is not referring to a, but defaults to the global window object. you need to assign the color to a variable, then use that variable as the value instead. Commented Apr 3, 2014 at 14:43

1 Answer 1

2

When you use $(this) in that scope, you're not referring to your anchor, you're probably referring to the Window object.

You can use:

$("a").each(function() {
    $(this).fluidbox({ overlayColor: $(this).data("color") });
});

This should work, since the function inside the "each" method changes the scope to each DOMElement you're iterating.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This works however because of your solution i found out that i tried the same thing before and dumped it. It turns out that that particual plugin Fluidbox changes options to a class that it applies globaly so the option is just rewritten everytime and latest rewrite is basicaly applied to everything. I will have to change the approach. Anyway this answer pushed me forwad and IS the solution to my question. Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.