I have a image dimensions calculation function which returns scaled image dimension values when it’s executed. (note: the list of images and their dimensions are accessed from the arrays.)
function setDesiredDimensions() {
var width = Math.min(imagesOrigWidths[currindex], desiredWidthLimit);
var height = Math.ceil((width / imagesOrigWidths[currindex]) * imagesOrigHeights[currindex]);
some more calculation code here...
return {width:width,height:height};
}
var size = setDesiredDimensions(imagesOrigWidths[currindex], imagesOrigHeights[currindex]);
Then I have some buttons in HTML:
<a id="button1"></a>
<a id="button2"></a>
<a id="button3"></a>
And various onclick events on these buttons, such as:
$('#button1').click( function() {
currindex = (currindex+1) % max;
**I need to evaluate setDesiredDimensions function here **
$("#imageswap").attr({src: imgSrcBase(imagesGuids[currindex]), width: size.width, height: size.height})
});
The buttons adjust the current image index in the array which I need to apply the dimension calculation on. BUT: I don’t want to have the same setDesiredDimensions function copied and pasted in all button click functions, but rather just access/evaluate it as a shortcut for a cleaner code.
I heard eval(); is dangerous and slow. Any ideas?
If you have define
setDesiredDimensionsin a scope accessible by all event handlers, you can just call the function. That’s what functions are for.I think your problem is that the function is working with global variables instead of arguments passed to it. In you example, you are passing
imagesOrigWidths[currindex]as argument but also accessimagesOrigWidths[currindex]inside the function, which does not make sense.Redefine it so that you can simply pass the arguments it needs, something like