Reputation: 548
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 calling setElemMargin()
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
Upvotes: 1
Views: 7011
Reputation: 865
Since setElemMarg is called within initDOM in the window.load event, then jquery/dom is not guaranteed to be ready. You need to call this function in the document load event
Upvotes: 0
Reputation: 263137
The problem resides in your setElemMarg()
function:
var setElemMarg = function(elem1, elem2, elemTrgt, propName) {
var margH = (getH(elem1) - getH(elem2)) / 2;
$(elemTrgt).css({propName : margH}); // <-- Here.
console.log(elem1, elem2, elemTrgt, propName, margH);
}
The literal object syntax you're using in your call to css()
results in jQuery trying to update a propName
style property instead of the property whose name is stored in propName
.
You can use bracket notation to work around this issue:
var styleProps = {};
styleProps[propName] = margH;
$(elemTrgt).css(styleProps);
Or simply call the two arguments form of css():
$(elemTrgt).css(propName, margH);
Upvotes: 3