I'm trying to figure out how to dynamically insert a margin into "mainImage". What I'm trying to do is vertically center the image, which has dynamic height and width (and dynamic client viewports). I can't figure out how to add the margins into the images as they're being loaded from javascript...
I have the following HTML:
<div id="content">
<img id="left" onclick="prevImage('images/52/image_','mainImage',52)" src="icons/arrow_left.png" />
<img id="right" onclick="nextImage('images/52/image_','mainImage',52)" src="icons/arrow_right.png"/>
<img id="mainImage" src="images/52/image_0.jpg" onload="addMargins()" />
</div>
with the following CSS:
div#content{
position: absolute;
margin-left: 20%;
margin-right: 5%;
width: 75%;
height: 95%;
text-align: center;
}
div#content img#left{
position: absolute;
left: 0;
top: 50%;
}
div#content img#right{
position: absolute;
right: 0;
top: 50%;
}
div#content img#mainImage{
max-height: 100%;
max-width: 95%;
}
and the javascript:
var key = 1;
function nextImage(thePath, id, max)
{
if(key == max)
{
key = 1;
}else{
key++;
}
var image = thePath + key + ".jpg";
document.getElementById(id).src= image;
};
function prevImage(thePath, id, max)
{
if(key == 1)
{
key = max;
}else{
key--;
}
var image = thePath + key + ".jpg";
document.getElementById(id).src= image;
};
So my idea was to do something in javascript that basically says:
"var viewport= viewport.height;
var mainImage= mainImage.height;
set marginTop to (viewport-mainImage)/2;
set marginBottom to (viewport-mainImage/2;"
and do that for each image as it loads via the "next/prev" buttons.
I wouldn't say this is the best way to do this. You probably want to look at using 'em's in your css to set the margins rather than doing it inline. The em's will ensure that the margins are relative to the size of the containing element.
However, if you want to do it this way, then you are on the right track. You will need to get a reference to the image and then set the marginTop property of the style.
var elem = document.getElementById(id); //reference to image
elem.style.marginTop = (viewport-mainImage)/2;
elem.style.marginBottom = (viewport-mainImage)/2;
I'm not 100% sure that your image will already have a height, so let me know if this works. If not, I'll check it out when I have a moment. Happy coding.