Recently I have been trying to delve into advanced (well for me) programming concepts like abstraction and functional programming etc. This has led me to experimenting w/ anon functions.
I have a situation where dynamically generated values are not being applied to a targeted element via an anonymous function using .css({}). I think it has something to do with false translations w/ object literals from my research.
Neither Chrome nor FF consoles are throwing any errors so here I am to ask the experts.
I made a fiddle, but it was not working very well. I am just going to link the resources involved on the dev site.
This is my dev site that I use to play/experiment and try out new things.
The js file: http://dev.kenstowell.net/scripts/scripts.js
Everything can be found through the debugger console, of course.
Ok, so here is what the intended behavior is:
-
On the
(window).load,initDOM()is called.$(window).load(function(){
//Style Initial Dom Elements
initDOM();
}); -
Inside of
initDom(), I attempt to set the top margin in relation to the parent container by callingsetElemMargin()and supplying it with the appropriate params.setElemMarg("#main-content-one", "#intro-text", "#intro-text", "margin-top"); -
setElemMarg()gets the height of the supplied args and uses them to calculate the margin to be set in the.css()map.var setElemMarg = function(elem1, elem2, elemTrgt, propName){
var margH = (getH(elem1) - getH(elem2)) / 2;
$(elemTrgt).css({propName : margH});
console.log(elem1, elem2, elemTrgt, propName, margH);
}var getH = function(elem){
return $(elem).height();
console.log($(elem).height());
} -
apply the calculated margin to
margin-top. (from above method)$(elemTrgt).css({propName : margH});
Thanks to anyone who looks at this. Please feel free to give me some constructive critique. Maybe some that you wish you had when you were a budding developer. 🙂
Ken
The problem resides in your
setElemMarg()function:The literal object syntax you’re using in your call to
css()results in jQuery trying to update apropNamestyle property instead of the property whose name is stored inpropName.You can use bracket notation to work around this issue:
Or simply call the two arguments form of css():