Lightbox moves image to bottom right corner - javascript

I'm writing a lightbox image gallery and struggling with the correct image positioning.
When clicking on an image, the lightbox appears. It's a completely new object generated with JS. By setting the margins, I move it to the screen middle (with z-index).
But these actions are performed before the image got time for loading. So JS doesn't have the required information clientWidth and clientHeight and uses 0 instead. This effects that the top left image corner (which is before loading the same as the other corners as well) is in the middle of the screen.
When the image starts loading, it will be extended to the bottom right.
How do I position the image correctly on the screen?
PS: No connection to the lightbox/lightbox2 library.
PPS: relevant code:
JS:
function lightbox(res, dsc) {
// lbimg: Lightbox-Image
var lbimg = document.createElement("img");
lbimg.src = res;
lbimg.id = "lbimg";
document.body.insertBefore(lbimg, document.body.firstChild);
lbimg.style.marginTop = "-" + Math.floor(lbimg.clientHeight/2.) + "px";
lbimg.style.marginLeft = "-" + Math.floor(lbimg.clientWidth/2.) + "px";
}
CSS:
#lbimg {
max-width: 70%;
max-height: 80%;
position: absolute;
left: 50%;
top: 50%;
border: 10px solid #fff;
z-index : 10;
}
HTML (only miniature images are displayed):
<div class="list">
<div><a onclick="lightbox('image.JPG', ''); "><img class="mini" src="image.JPG_MINI.jpg" /></a></div>
<!--other images are defined analogous-->
</div>

function lightbox(res, dsc) {
var lbimg = document.createElement("img");
lbimg.id = "lbimg";
lbimg.onload = function() {
document.body.insertBefore(lbimg, document.body.firstChild);
lbimg.style.marginTop = "-" + Math.floor(lbimg.clientHeight/2) + "px";
lbimg.style.marginLeft = "-" + Math.floor(lbimg.clientWidth/2) + "px";
};
lbimg.src = res;
}
You have to wrap both the DOM insertion and style setting in a load handler (if you wrap only style changes, you will see element "shifting" after insertion). Also set your src after binding the load handler, otherwise it's possible Internet Explorer will miss the handler (when loading images from cache).

Try wrapping your margin calculations inside an onload call:
lbimg.onload = function () {
lbimg.style.marginTop = "-" + Math.floor(lbimg.clientHeight/2.) + "px";
lbimg.style.marginLeft = "-" + Math.floor(lbimg.clientWidth/2.) + "px";
};
This will ensure that the height and width are available to the JS in order that the margins can be calculated correctly.

Related

set iframe height dynamically depending on content [duplicate]

I am loading an aspx web page in an iframe. The content in the Iframe can be of more height than the iframe's height. The iframe should not have scroll bars.
I have a wrapper div tag inside the iframe which basically is all the content. I wrote some jQuery to make the resize happen :
$("#TB_window", window.parent.document).height($("body").height() + 50);
where
TB_window is the div in which the Iframe is contained.
body - the body tag of the aspx in the iframe.
This script is attached to the iframe content. I am getting the TB_window element from the parent page. While this works fine on Chrome, but the TB_window collapses in Firefox. I am really confused/lost on why that happens.
You can retrieve the height of the IFRAME's content by using:
contentWindow.document.body.scrollHeight
After the IFRAME is loaded, you can then change the height by doing the following:
<script type="text/javascript">
function iframeLoaded() {
var iFrameID = document.getElementById('idIframe');
if(iFrameID) {
// here you can make the height, I delete it first, then I make it again
iFrameID.height = "";
iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + "px";
}
}
</script>
Then, on the IFRAME tag, you hook up the handler like this:
<iframe id="idIframe" onload="iframeLoaded()" ...
I had a situation a while ago where I additionally needed to call iframeLoaded from the IFRAME itself after a form-submission occurred within. You can accomplish that by doing the following within the IFRAME's content scripts:
parent.iframeLoaded();
A slightly improved answer to Aristos...
<script type="text/javascript">
function resizeIframe(iframe) {
iframe.height = iframe.contentWindow.document.body.scrollHeight + "px";
}
</script>
Then declare in your iframe as follows:
<iframe onload="resizeIframe(this)" ...
There are two minor improvements:
You don't need to get the element via document.getElementById - as you already have it in the onload callback.
There's no need to set the iframe.height = "" if you're going to reassign it in the very next statement. Doing so actually incurs an overhead as you're dealing with a DOM element.
Edit:
If the content in the frame is always changing then call:
parent.resizeIframe(this.frameElement);
from within the iframe after the update. Works for same origin.
Or to auto detect:
// on resize
this.container = this.frameElement.contentWindow.document.body;
this.watch = () => {
cancelAnimationFrame(this.watcher);
if (this.lastScrollHeight !== container.scrollHeight) {
parent.resizeIframeToContentSize(this.frameElement);
}
this.lastScrollHeight = container.scrollHeight;
this.watcher = requestAnimationFrame(this.watch);
};
this.watcher = window.requestAnimationFrame(this.watch);
I found that the accepted answer didn't suffice, since X-FRAME-OPTIONS: Allow-From isn't supported in safari or chrome. Went with a different approach instead, found in a presentation given by Ben Vinegar from Disqus. The idea is to add an event listener to the parent window, and then inside the iframe, use window.postMessage to send an event to the parent telling it to do something (resize the iframe).
So in the parent document, add an event listener:
window.addEventListener('message', function(e) {
var $iframe = jQuery("#myIframe");
var eventName = e.data[0];
var data = e.data[1];
switch(eventName) {
case 'setHeight':
$iframe.height(data);
break;
}
}, false);
And inside the iframe, write a function to post the message:
function resize() {
var height = document.getElementsByTagName("html")[0].scrollHeight;
window.parent.postMessage(["setHeight", height], "*");
}
Finally, inside the iframe, add an onLoad to the body tag to fire the resize function:
<body onLoad="resize();">
Add this to the iframe, this worked for me:
onload="this.height=this.contentWindow.document.body.scrollHeight;"
And if you use jQuery try this code:
onload="$(this).height($(this.contentWindow.document.body).find(\'div\').first().height());"
you could also add a repeating requestAnimationFrame to your resizeIframe (e.g. from #BlueFish's answer) which would always be called before the browser paints the layout and you could update the height of the iframe when its content have changed their heights. e.g. input forms, lazy loaded content etc.
<script type="text/javascript">
function resizeIframe(iframe) {
iframe.height = iframe.contentWindow.document.body.scrollHeight + "px";
window.requestAnimationFrame(() => resizeIframe(iframe));
}
</script>
<iframe onload="resizeIframe(this)" ...
your callback should be fast enough to have no big impact on your overall performance
There are four different properties you can look at to get the height of the content in an iFrame.
document.documentElement.scrollHeight
document.documentElement.offsetHeight
document.body.scrollHeight
document.body.offsetHeight
Sadly they can all give different answers and these are inconsistant between browsers. If you set the body margin to 0 then the document.body.offsetHeight gives the best answer. To get the correct value try this function; which is taken from the iframe-resizer library that also looks after keeping the iFrame the correct size when the content changes,or the browser is resized.
function getIFrameHeight(){
function getComputedBodyStyle(prop) {
function getPixelValue(value) {
var PIXEL = /^\d+(px)?$/i;
if (PIXEL.test(value)) {
return parseInt(value,base);
}
var
style = el.style.left,
runtimeStyle = el.runtimeStyle.left;
el.runtimeStyle.left = el.currentStyle.left;
el.style.left = value || 0;
value = el.style.pixelLeft;
el.style.left = style;
el.runtimeStyle.left = runtimeStyle;
return value;
}
var
el = document.body,
retVal = 0;
if (document.defaultView && document.defaultView.getComputedStyle) {
retVal = document.defaultView.getComputedStyle(el, null)[prop];
} else {//IE8 & below
retVal = getPixelValue(el.currentStyle[prop]);
}
return parseInt(retVal,10);
}
return document.body.offsetHeight +
getComputedBodyStyle('marginTop') +
getComputedBodyStyle('marginBottom');
}
Other answers were not working for me so i did some changes. Hope this will help
$('#iframe').on("load", function() {
var iframe = $(window.top.document).find("#iframe");
iframe.height(iframe[0].ownerDocument.body.scrollHeight+'px' );
});
Just in case this helps anyone. I was pulling my hair out trying to get this to work, then I noticed that the iframe had a class entry with height:100%. When I removed this, everything worked as expected. So, please check for any css conflicts.
I am using jQuery and the code below working for me,
var iframe = $(window.top.document).find("#iframe_id_here");
iframe.height(iframe.contents().height()+'px' );
You can refer related question here - How to make width and height of iframe same as its parent div?
To set dynamic height -
We need to communicate with cross domain iFrames and parent
Then we can send scroll height/content height of iframe to parent window
And codes - https://gist.github.com/mohandere/a2e67971858ee2c3999d62e3843889a8
Rather than using javscript/jquery the easiest way I found is:
<iframe style="min-height:98vh" src="http://yourdomain.com" width="100%"></iframe>
Here 1vh = 1% of Browser window height. So the theoretical value of height to be set is 100vh but practically 98vh did the magic.
All other answers are correct but what if the iframe has some dynamic content like a map that loads later and dynamically changes your iframe scroll height. This is how I achieved it.
var iFrameID = document.getElementById('idIframe');
intval = setInterval(function(){
if(iFrameID.scrollHeight == iFrameID.contentWindow.document.body.scrollHeight){
clearInterval(intval);
}else{
iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + "px";
}
},500)
I simply wrap the code inside setInterval which matches the iframe scroll height with iframe content scroll height then clear the interval.
in my project there is one requirement that we have make dynamic screen like Alignment of Dashboard while loading, it should display on an entire page and should get adjust dynamically, if user is maximizing or resizing the browser’s window.
For this I have created url and used iframe to open one of the dynamic report which is written in cognos BI.In jsp we have to embed BI report. I have used iframe to embed this report in jsp. following code is working in my case.
<iframe src= ${cognosUrl} onload="this.style.height=(this.contentDocument.body.scrollHeight+30) +'px';" scrolling="no" style="width: 100%; min-height: 900px; border: none; overflow: hidden; height: 30px;"></iframe>
I found the answer from Troy didn't work. This is the same code reworked for ajax:
$.ajax({
url: 'data.php',
dataType: 'json',
success: function(data)
{
// Put the data onto the page
// Resize the iframe
var iframe = $(window.top.document).find("#iframe");
iframe.height( iframe[0].contentDocument.body.scrollHeight+'px' );
}
});
To add to the chunk of window that seems to cut off at the bottom, especially when you don't have scrolling I used:
function resizeIframe(iframe) {
var addHeight = 20; //or whatever size is being cut off
iframe.height = iframe.contentWindow.document.body.scrollHeight + addHeight + "px";
}
This one is useful when you require a solution with no jquery. In that case you should try adding a container and set a padding to it in percentages
HTML example code:
<div class="iframecontainer">
<iframe scrolling="no" src="..." class="iframeclass"width="999px" height="618px"></iframe>
</div>
CSS example code:
.iframeclass{
position: absolute;
top: 0;
width: 100%;
}
.iframecontainer{
position: relative;
width: 100%;
height: auto;
padding-top: 61%;
}
The simple solution is to measure the width and height of the content area, and then use those measurements to calculate the bottom padding percentage.
In this case, the measurements are 1680 x 720 px, so the padding on the bottom is 720 / 1680 = 0.43 * 100, which comes out to 43%.
.canvas-container {
position: relative;
padding-bottom: 43%; // (720 ÷ 1680 = 0.4286 = 43%)
height: 0;
overflow: hidden;
}
.canvas-container iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
A slightly improved answer to BlueFish...
function resizeIframe(iframe) {
var padding = 50;
if (iframe.contentWindow.document.body.scrollHeight < (window.innerHeight - padding))
iframe.height = iframe.contentWindow.document.body.scrollHeight + "px";
else
iframe.height = (window.innerHeight - padding) + "px";
}
This takes in consideration the height of the windows screen(browser, phone) which is good for responsive design and iframes that have huge height.
Padding represents the padding you want above and below the iframe in the case it goes trough whole screen.
jQuery('.home_vidio_img1 img').click(function(){
video = '<iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>';
jQuery(this).replaceWith(video);
});
jQuery('.home_vidio_img2 img').click(function(){
video = <iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>;
jQuery('.home_vidio_img1 img').replaceWith(video);
jQuery('.home_vidio_img1 iframe').replaceWith(video);
});
jQuery('.home_vidio_img3 img').click(function(){
video = '<iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>';
jQuery('.home_vidio_img1 img').replaceWith(video);
jQuery('.home_vidio_img1 iframe').replaceWith(video);
});
jQuery('.home_vidio_img4 img').click(function(){
video = '<iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>';
jQuery('.home_vidio_img1 img').replaceWith(video);
jQuery('.home_vidio_img1 iframe').replaceWith(video);
});
Sample using PHP htmlspecialchars() + check if height exists and is > 0:
$my_html_markup = ''; // Insert here HTML markup with CSS, JS... '<html><head></head><body>...</body></html>'
$iframe = '<iframe onload="if(this.contentWindow.document.body.scrollHeight) {this.height = this.contentWindow.document.body.scrollHeight;}" width="100%" src="javascript: \''. htmlspecialchars($my_html_markup) . '\'"></iframe>';
Script
<script type="text/javascript" language="javascript">
$(document).ready(function(){
var height = $(window).height();
$('.myIframe').css('height', height - 200);
});
</script>
iframe
<iframe class="myIframe" width="100%"></iframe>
It's working in my case.
$(document).height() // - $('body').offset().top
and / or
$(window).height()
See Stack Overflow question How to get the height of a body element.
Try this to find the height of the body in jQuery:
if $("body").height()
It doesn't have a value if Firebug. Perhaps that's the problem.
just make iframe container position:absolute and iframe will automatically change its height according to its content
<style>
.iframe-container {
display: block;
position: absolute;
/*change position as you need*/
bottom: 0;
left: 0;
right: 0;
top: 0;
}
iframe {
margin: 0;
padding: 0;
border: 0;
width: 100%;
background-color: #fff;
}
</style>
<div class="iframe-container">
<iframe src="http://iframesourcepage"></iframe>
</div>

Matching div height to combined height of other divs

I'm trying to match the height of background div to the combined height of divs in front. I used simple jQuery height function and it kind of worked:
var originalHeight = $("#topbg").height() + $("#menurowbg").height() + $("#headerbg").height() + $("#contentareabg").height() + $("#footerbg").height();
$("#wrapper").height(originalHeight);
The problem is, the height needs to change dynamically if one of those divs is resized to keep matching. I tried to put the setTimeout function, but failed. I'm obviously missing something but can't figure it out. Please help this jQuery rookie. Here's my current code:
var originalHeight = $("#topbg").height() + $("#menurowbg").height() + $("#headerbg").height() + $("#contentareabg").height() + $("#footerbg").height();
setTimeout function checkHeight() {
if(originalHeight < ($("#topbg").height() + $("#menurowbg").height() + $("#headerbg").height() + $("#contentareabg").height() + $("#footerbg").height()))
{
originalHeight = $("#topbg").height() + $("#menurowbg").height() + $("#headerbg").height() + $ ("#contentareabg").height() + $("#footerbg").height();
}
}, 500);
$("#wrapper").height(originalHeight);
There are three scenarios:
1) Use setInterval() rather than setTimeout() to execute code ever X amount of milliseconds:
setInterval(function() {
setContainerSize();
}, 1000);
Example: http://jsfiddle.net/XWmdL/3/
2) The containing div is the parent of the divs being resized. In that case, You don't have to add all the heights together and reset the container's height. You can just set the container's width and height attributes to auto:
#container {
width: auto;
height: auto;
}
Example: http://jsfiddle.net/XWmdL/1/
3) If your child divs are being resized when the window size changes, you need to use the $(window).resize() event. Change the viewing window size in the following example and you'll see the red background size change as the yellow div changes.
Example: http://jsfiddle.net/XWmdL/2/
Hope this helps!
First the condition is wrong
setTimeout function checkHeight() {
if(originalHeight < (jQuery("#topbg").height() + jQuery("#menurowbg").height() + jQuery("#headerbg").height() + jQuery("#contentareabg").height() + jQuery("#footerbg").height())) {
originalHeight = jQuery("#topbg").height() + jQuery("#menurowbg").height() + jQuery("#headerbg").height() + jQuery("#contentareabg").height()+jQuery("#footerbg").height();
jQuery("#wrapper").height(originalHeight);
}, 500);

how to center and make various images sizes fit in a container

I'm using bxslider to have a carousel of images. The thing is though, the images it receives to display are of somewhat unpredictable sizes. The container size is 243x243. And we know that no image will have a side smaller than 243. So...I'd like to center the image in the container. And either zoom in until the shorter of the two dimensions (L vs W) fills the container at 243, and the longer dimension overflow is hidden.
For the images I'm working with, doing this will be perfect for getting the important details of the picture in the frame.
But I'm having trouble...
I've tried the following to center the picture in the frame:
jQuery(".bx-container").each(function() {
var img_w = jQuery(this).children("img").width();
var img_h = jQuery(this).children("img").height();
var pos_top = (img_h - containerHeight) / 2;
var pos_left = (img_w - containerWidth) / 2;
var pos_top = (243 - img_h) / 2;
var pos_left = (243 - img_w) / 2;
jQuery(this).children("img").css({
'top' : pos_top + 'px',
'left' : pos_left + 'px'
});
});
And I've tried this to position not square images into the frame:
jQuery(".bx-container").each(function(){
var refRatio = 1;
var imgH = jQuery(this).children("img").height();
var imgW = jQuery(this).children("img").width();
if ( (imgW/imgH) < refRatio ) {
jQuery(this).addClass("bx-portrait");
} else {
jQuery(this).addClass("bx-landscape");
}
});
});
I've messed with both scripts and the css but I just can't seem to get it work. It either centers but doesn't resize right. Or resizes but centers wrong. Or does both wrong.
Here's the jsfiddle: http://jsfiddle.net/vgJ9X/298/
Could someone help me out?
Thanks!
EDIT:
New jsfiddle...the portrait ones work right. The landscape images still squish. :(
http://jsfiddle.net/vgJ9X/307/
EDIT:
I THINK it has something to do with relatively positioned elements not being allowed to overlap. Trying to find a fix. If anyone knows, edit the last fiddle I posted.
jQuery(".bx-container img").each(function () {
var w = jQuery(this).width();
var h = jQuery(this).height();
if (w > h) $(this).addClass('bx-landscape');
else $(this).addClass('bx-portrait');
});
Check this Updated JSFiddle
Update
jQuery(".bx-container img").each(function () {
var w = jQuery(this).width();
var h = jQuery(this).height();
if (w > h){
$(this).addClass('bx-landscape');
var trans= -243/2;
$(this).css('-webkit-transform','translateZ('+trans+'px)');
}
else if(h > w){
$(this).addClass('bx-portrait');
var trans= -243/2;
$(this).css('-webkit-transform','translateY('+trans+'px)');
}
});
check this JSFiddle
Update of Update
Found the issue with landscape, the plugin is setting max-width:100%; overriding it with max-width:none; fixes the issue...
Update Of Updated Fiddle
Try this:
img{
position:relative;
height:100%;
width:300px;
}
Simple an clean.
Demo: http://jsfiddle.net/vgJ9X/302/
I did a couple things to your jsfiddle.
First I changed the order of your resize and center functions, so the resize comes first. This way, the smaller images get resized, then centered. I also uncommented the first portion of your code.
You also had a couple of errors in your css. There was an extra closing bracket after img style declaration. Your .bx-portrait img and .bx-landscape img declarations were set to 100%px;.
Update:
Change the css in your two .bx classes to:
.bx-portrait img {
height: 100%;
width: auto;
}
.bx-landscape img {
height: auto;
width: 100%;
}
And add a clearfix to your ul:
.bxslider:after {
content: '';
clear: both;
display: table;
padding: 0;
margin: 0;
}
The height is clipping because .bx-viewport has a set height of 243px but also has a 5px border, which makes the actual internal height 233px. You'll need to make the height 253px to account for the 10px of border. This is why they don't look centered vertically.
DEMO
Why don't you just use background images instead and center them. Here is a demo from your original code
http://jsfiddle.net/8y8df/
If you want to show the full size image, just remove the background-size:contain; from the css.

White space on right of page

How do I get rid of that undesired white border on the right of the page?
The website basically dynamically resizes images on a grid, here's a video: https://vine.co/v/h2wtnw6K3H0
CSS:
body {
height: 100%;
width: 100%;
margin: 0;
}
grid {
height: 100%;
width: 100%;
}
.gridImage {
vertical-align: bottom;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
margin-bottom: 0px;
}
JS:
function resize() {
console.log($(window).width());
var newBody = "";
for (var i = 0; i <= 100; i++) {
newBody += '<img class="gridImage" src="Images/image2.jpg" width="' + $(window).width() / Math.floor(($(window).width() / 100)) + 'px" height="' + $(window).width() / Math.floor(($(window).width() / 100)) + 'px">';
}
document.getElementById("grid").innerHTML = newBody;
}
If my margins are zero, why is this showing up? Anything I'm missing? Thanks.
Ridcully has covered what the problem is, but here’s a solution.
First you would need to calculate the desired width of each image. This is simply your current equation wrapped in Math.ceil().
var windowWidth = $(window).width() // A slight performance improvement, plus cleaner code
var maxImageWidth = <your value here>
var unroundedImageWidth = windowWidth / Math.floor(windowWidth / maxImageWidth)
var roundedImageWidth = Math.ceil(unroundedImageWidth)
Unless your images fit perfectly, this will make each row slightly wider than the window, causing the final image on each line to wrap to the next. To prevent this, you need to set the gridContainer’s width to that of each row.
$('.gridContainer').width(windowWidth * roundedImageWidth / unroundedImageWidth)
Everything should look good, except for one thing: the horizontal scrollbar. This is easily fixed, however. Add this to your CSS:
.gridContainer {
overflow-x: hidden;
}
This will hide both the scrollbar and the final few pixels on each line. Perfect! Well, not quite.
The problem with this method is that one image per row takes the hit (loses pixels) for all of the others. If you have small images and a lot of images per row, you could end up losing a significant portion of your final column.
To avoid this, you can round your image widths upwards and distribute the overflow amongst all images in the row. This is a little more complicated than the previous method, but it does give a better result.
There are three more numbers you need to calculate.
var imagesPerRow = windowWidth / unroundedImageWidth
var numOfRows = Math.ceil($('.gridContainer img').length / imagesPerRow)
var spillage = windowWidth / roundedImageWidth - windowWidth // Pixels we have to lose
Now it’s just a matter of distributing the spillage.
var i = 0 // Loop counter
while (spillage !== 0) {
// Set the width of all images in column i to the width of that column - 1
$('.gridContainer img:nth-child(' + imagesPerRow + 'n-' + (i+1) + ')')
.width($('.gridContainer img:nth-child(' + (i+1) + ')').width() - 1)
spillage--
i++
}
There should no longer be more than a single pixel difference between the widths of the images.
It's because of rounding errors. What you do is fill the grid with 100 scaled images, depending on the browser to wrap to a new line when the image doesn't fit in the current row any more.
Now imagine a width of 305 pixels. Your formula gives an image width of 100 for that, so you get 3 images in a row and the next one wraps to the next row, leaving 5 pixels blank at the right border.
i think you should also add padding:0; to body its missing from your code.
Try it and even better just make a jsfiddle then it would be easier to check for everyone.

Lightbox Centering in jquery

Recently I tried to make the images in lightbox. If you click the image it show off in lightbox effect. But Some of the Reason, Lightbox is not centering properly in a window size. For Example if you click the image it loaded in lightbox but for the first time it lightbox load in bottom of the site and again you click the image it align properly.
here is the screenshot what i exactly saying.
First Screenshot looks when you click the image when page load.
First Time Click the Image:
Second Time Click the Image:
For the First Time it getting alignment problem.
For the Second Time it not getting alignment problem(Without Page Load)
Javascript:
<script>
jQuery(document).ready(function() {
jQuery("img").click(function() {
var img_path;
if ($(this).parent('a').length) {
img_path = $(this).parent('a').prop('href');
}
else
{
img_path = $(this).attr('src');
}
jQuery(".cplightbox1").html(jQuery("<img>").attr("src", img_path));
jQuery(".cpoutter").css('display', 'block');
jQuery('.cpoutter').animate({'opacity': '1'});
//jQuery('.lightbox').animate({'opacity':'1.00'});
var cplightbox = document.getElementsByClassName('cplightbox')[0];
var cpoutter = document.getElementsByClassName('cpoutter')[0];
cplightbox.style.marginTop = ((cpoutter.offsetHeight / 2) - (cplightbox.offsetHeight / 2)) + "px";
return false;
});
});
</script>
HTML CODE:
Here is the Fiddle
http://jsfiddle.net/rCUGD/7/
But Some How this Script is working properly in jsfiddle.net. May Be I messup with script or css
I am Not where i made a mistake
EDITED:
Now After #JustAnil Here is the Screenshot:
After the second click it should show like this normal
Checkout this working JSFiddle.
You need to change the following lines (where you calculate the offset).
Change the following lines:
var cplightbox = document.getElementsByClassName('cplightbox')[0];
var cpoutter = document.getElementsByClassName('cpoutter')[0];
cplightbox.style.marginTop = ((cpoutter.offsetHeight / 2) - (cplightbox.offsetHeight / 2)) + "px";
To:
var cplightbox = document.getElementsByClassName('cplightbox')[0];
// We need the actual height of the image so grab it from the "inner" container
var cplightbox1 = document.getElementsByClassName('cplightbox1')[0]; // New Line
var cpoutter = document.getElementsByClassName('cpoutter')[0];
// Calculate the (negative) offset from the width & height
cplightbox.style.marginLeft = "-"+$(cplightbox1).width() / 2 + "px";
cplightbox.style.marginTop = "-"+$(cplightbox1).height() / 2 + "px";
// ^ Negative offset so we can vertically and horizontally center it.
Finally
Change your CSS from:
.cplightbox {
margin-left: auto;
margin-right:auto;
width:auto;
height:auto;
display:inline-block;
}
To:
.cplightbox {
position:fixed;
top:50%;
left:50%;
display:inline-block;
}
Checkout this question CSS Vertically & Horizontally Center Div (Thats how to center a div to the middle of the screen).
Then alter your javascript to calculate the negative offset (dependant on how big the picture is [ie 50% of the width & height])
View this working JSFiddle.

Categories