First, I apologize. I know what I want to do, but not what I should call it or quite how to ask it, so my googling was unfruitful.
I have some animation I’m using to show/hide text. I’m trying to wrap it up all nice in an object, but the way I’m doing it, I have to run some calculation code each time, as I don’t know which section it is being stored with.
Now, what I hate is that I’m re-running a calculatePositions(entry); function on every pass rather than using a saved value. Trouble is, this will happen on multiple elements so the positions array needs to change. Is there a way save the positions array to a specific DOM element and just calculate it once? Can I attach these functions and properties to DOM elements rather than pass in the entry object every time?
My code:
var theShort = {};
theShort.toggle = function(){
var positions = new Array;
function calculatePositions(entry){
/*
positions = Nasty calculation code
*/
}
function showLong(entry){
calculatePositions(entry);
//My toggle code is obviously more complex and uses the positions array.
//But for simplicity sake, I've omitted it
$(entry).find('.tsl-theshort').show();
$(entry).find('.tsl-thelong').hide();
}
function showShort(entry){
calculatePositions(entry);
$(entry).find('.tsl-theshort').show();
$(entry).find('.tsl-thelong').hide();
}
return {
init: function (){
$('.tsl-showLong').click(function(){
showLong($(this).closest('.entry-content'));
return false;
});
$('.tsl-showShort').click(function(){
showShort($(this).closest('.entry-content'));
return false;
});
}
};
}();
jQuery(document).ready(function($){
theShort.toggle.init();
});
If you’re worried about running the calculation function every time, set up a cache based on the element’s id. If each element has a unique ID in the dom, you could do something like
Then, when you wish to lookup the calculation of an element,