I have 4 textboxes that make up an input for a text-shadow property, and are contained within a DIV like so:
<div id="shadow">
<input type="number" min="-5" max="5" step="1" value="0" id="hshad" />
<input type="number" min="-5" max="5" step="1" value="0" id="vshad" />
<input type="number" min="0" max="20" step="1" value="0" id="bshad" />
<input type="text" value="#000000" id="cshad" />
</div>
Right now, I manually combine the four inputs to get a desired css value. Something like this:
$('#elem').css('text-shadow', $('#hshad').val() + "px " + $('#vshad').val() + "px " + $('#bshad').val() + "px " + $('#cshad').val());
Is there a way I could ‘map’ these values to the value of #shadow as both a getter and a setter?
For example $('#shadow').val() would give me
"0px 1px 5px #FFFFFF"
And I could set the values of the four inputs by doing:
$('#shadow').val("0px 1px 5px #FFFFFF")
This is pretty much for the purpose (because I know you’ll ask) of being able to loop through CSS rules and set form field values when editing a record that has pre-exiting rules. This all goes to a wicked WYSIWYG I’m making.
EDIT
Ok, so it’s important for the sake of this question to pass back from val(). I’m looping through ~20-30 CSS rules, and don’t want to have to get stumped on a single rule. I could just go back after the loop and break apart the value, but I was hoping to extend val and keep my code in a nice, tidy loop.
Example
My CSS to loop (as JSON object)”
{
"top": "48px",
"left": "59px",
"width": "100px",
"height": "100px",
"font-family": "Oxygen",
"font-size": "1em",
"font-weight": "normal",
"color": "rgb(51, 51, 51)",
"text-shadow": "rgb(0, 0, 0) 1px 0px 0px",
"background-color": "rgba(0, 0, 0, 0)",
"border-radius": "0px",
"-moz-border-radius": "0px",
"box-shadow": "none",
"-moz-box-shadow": "none",
"padding": "0px"
}
I give each form field a data-prop attribute for its associated CSS property like so:
<input type="text" data-prop="font-family" />
Then I would loop the rules like so
$.each(cssRules, function(name, value) {
$('[data-prop=' + name + ']').val(value);
})
Nice, neat, and cozy.
http://jsfiddle.net/XCCgv/4/
Edit: I saw your edit but I think you get the idea from here… you can check
$(elem).data()in the valHook and call a different function depending on that. Here I am just checking for.id === "shadow"