Centering via offset math doesn't work in non-webkit browsers - javascript

The code: http://jsfiddle.net/LPF85/6/
In FF, IE7, and IE9 (the only browsers I've tested that don't run WebKit), it seems that the left attribute is either always set to 0, or, in IE's case, negative.
My positioning code is all based off the dimensions of the document.
function open_img_in_face_box(id, width){
max_width = $j(document).width();
max_height = $j(document).height();
padding = 150;
passed_width = width || (max_width - (2 * padding));
var img = $j('#' + id);
dom_img = document.getElementById(id);
$j(document).bind('reveal.facebox', function() {
$j("#facebox .image img").width(passed_width);
})
// display
jQuery.facebox({
image: img.attr('src')
});
// center and adjust size
var aspect_ratio = img.width() / img.height();
var img_width = passed_width;
var img_height = passed_width / aspect_ratio;
window_center_y = max_height / 2;
window_center_x = max_width / 2;
offset_y = window_center_y - (img_height / 2);
offset_x = window_center_x - (img_width / 2);
var fbx = $j('#facebox');
fbx.css('position', 'absolute');
fbx.css('left', offset_x + 'px !important');
fbx.css('top', offset_y + 'px !important');
fbx.css('margin-left', 'auto');
fbx.css('margin-right', 'auto');
}
margin-left and margin-right don't appear to do anything here, which I'm fine with, because the left math should work across all browsers, right? (It is just math)
The goal of the facebox / lightbox, is to be centered both horizontally and vertically.

Why would you even programatically calculate the position in the first place? What if the user resizes the page? This can easily be done in pure CSS.
I don't really understand your jsFiddle (or am I not seeing the same thing?) so I'll just give you this script: http://jsfiddle.net/minitech/8U4Ke/ that can be modified however you like. It's commented. ;)
Now it's easy to hide and show - to hide, fade out .overlay. To show, fade it in. To change the contents, replace the HTML in .popup. Add close boxes and whatnot liberally.

Related

Image orientation lost when resizing with javascript

I need to show an image in the largest size possible so I use javascript to create a square div with the maximum dimensions that fit the browser window.
I load the image and then I then change the width and height attributes to values that will make the image fit.
This works fine for 99% of images, but I have some that are shown in landscape format when they actually in portrait. I know they should be portrait because they are shown correctly in Windows explorer, Photoshop etc, and even when I right-click on the displayed image in a browser and select "show image in new window"
I have even rotated the image with PhotoShop and it is still shown landscape.
This makes me think that metadata is not being respected.
In ASPX Page_Load... imgImage.ImageUrl = "~/" & tPath
In HTML
function resizeImg() {
var windowWidth = window.innerWidth || document.documentElement.clientWidth;
var windowHeight = window.innerHeight || document.documentElement.clientHeight;
var imgMax = windowHeight - 54;
var div = document.getElementById('divImage');
div.style.width = imgMax + 'px';
div.style.height = imgMax + 'px';
var divW = div.offsetWidth;
var divH = div.offsetHeight;
var winR = divW/divH
var newImgH = imgH;
var newImgW = imgW;
if(newImgW > divW) {
newImgW=divW
newImgH = Math.floor(Math.round(divW / imgR));
}
if(newImgH > divH) {
newImgH=divH
newImgW =Math.floor(Math.round(divH * imgR));
}
img.setAttribute('width',newImgW);
img.setAttribute('height',newImgH);
img.setAttribute('hspace',(divW - newImgW)/2);
img.setAttribute('vspace', (divH - newImgH) / 2);
}

Avoid right jump of elements with javascript and local variable when hiding vertical scrollbar

I would like to add left margin and right margin to the body to hide the width change when I hide the vertical scrollbar.
I have this code that finds the width of the vertical scrollbar:
var $outer = $('<div>').css({visibility: 'hidden', width: 100, overflow: 'scroll'}).appendTo('body'),
widthWithScroll = $('<div>').css({width: '100%'}).appendTo($outer).outerWidth();
$outer.remove();
var scrollbarwidth = 100 - widthWithScroll;
It gives the value "17" (in pixels) for IE11, Chrome 45, and Firefox 39 (desktop).
When I hide the vertical scrollbar, all elements, such as images, jump exactly 17 pixels to the right, which I want to hide.
I have tried:
document.body.style.marginRight = scrollbarwidth + "px";
$('body').css('margin-right', scrollbarwidth);
$(body).css("marginRight", scrollbarwidth + "px");
The last one might be faulty in some way, since other parts of the function stops working when it's enabled. The two others don't seem to work either, as I don't see any margin changes.
EDIT 1: For easier understanding of how I am going to use it, I wanted to mention that it's supposed to trigger on a on scroll function, like this:
var check1 = false;
$(document).bind('scroll', function() {
if(check1 === false && $(window).scrollTop() >= $('#divscrolltester').offset().top + $('#divscrolltester').outerHeight() - window.innerHeight) {
check1 = true;
unloadScrollBars();
disableScroll();
var $outer = $('<div>').css({visibility: 'hidden', width: 100, overflow: 'scroll'}).appendTo('body'),
widthWithScroll = $('<div>').css({width: '100%'}).appendTo($outer).outerWidth();
$outer.remove();
var scrollbarwidth = 100 - widthWithScroll;
//document.body.style.paddingRight = scrollbarwidth + "px"; Temporary disabled.
//$('body').css('padding-right', scrollbarwidth); Temporary disabled.
//$(body).css("marginRight", scrollbarwidth + "px"); Temporary disabled.
setTimeout(function() {
enableScroll();
reloadScrollBars();
//document.body.style.paddingLeft = scrollbarwidth + "px"; Temporary disabled.
//$('body').css('padding-left', scrollbarwidth); Temporary disabled.
//$(body).css("marginLeft", scrollbarwidth + "px"); Temporary disabled.
}, 500);
}
});
EDIT 2:
Here is a Fiddle to show most of the js, html and css: https://jsfiddle.net/tfnwj7dj/10/.
I haven't added the change of css through code yet, as I'm still trying to solve the issue. Also, the scrolling and scrollbar are supposed to be re-enabled in a second, but there seems to be an error in there somewhere, sorry.
EDIT 3:
For your information at this moment, these lines work:
document.body.style.paddingLeft = (scrollbarwidth) + "px";
$('body').css('padding-left', scrollbarwidth);
document.body.style.paddingRight = (scrollbarwidth) + "px";
$('body').css('padding-right', scrollbarwidth);
document.body.style.marginLeft = (scrollbarwidth) + "px";
$('body').css('margin-left', scrollbarwidth);
document.body.style.marginRight = (scrollbarwidth) + "px";
$('body').css('margin-right', scrollbarwidth);
Maybe you have enough information to solve it, if you have the same issue, but unfortunately, this wasn't enough for me. It might be important info to know that I have my content centered with a width / max-width of just 500px, and that I don't actually have a body class. Maybe on designs with width="100%", or elements with absolute positioning, the lines might be enough.
Both javascript and jquery solutions are welcomed.
EDIT 4:
I finally solved it for my own circumstances - feel free to read the answer below. It works for preventing elements to jump when hiding the vertical scrollbar, and with some tinkering, it could probably do for a body class, or other situations.
Is your scrollbarwidth integer? Try this
var scrollbarwidth = 100;
$('body').css('margin-right', scrollbarwidth);
Maybe you have wrong value at scrollbarwidth ? In my ff this code works.
I managed to solve it - I'd like to clarify that my css actually don't contain a body class, and that I just centered all elements with a width / max-width of 500px and margin-left/right auto.
For my and other, similar cases, here is the answer:
/* First 5 lines for finding the scrollbar width. */
var $outer = $('<div>').css({visibility: 'hidden', width: 100, overflow: 'scroll'}).appendTo('body'),
widthWithScroll = $('<div>').css({width: '100%'}).appendTo($outer).outerWidth();
$outer.remove();
var scrollbarwidth = 100 - widthWithScroll;
var scrollbarwidthadjustment = scrollbarwidth / 2; /* For centered elements, divide the scrollbar width by 2. */
var element = document.getElementById('element');
element.style.right = (scrollbarwidthadjustment) + "px";
And when you re-enable the vertical scrollbar, simply add:
element.style.right = "0px";
Also, the element must have a css position stated, otherwise it won't trigger. Here is an example of a css style that works:
.examplestyle {
color: white;
position: relative;
margin-left: auto;
margin-right: auto;
max-width: 100%;
display: block;
}
EDIT 1:
To prevent some unsightly css errors on mobile devices, add these lines:
/* ... */
var scrollbarwidthadjustment = scrollbarwidth / 2;
var windowWidth = $(window).width(); /* Get current window width on click/scroll etc. */
var window1 = windowWidth + scrollbarwidth; /* Window width + scrollbar width. */
var element = document.getElementById('element');
if(window1 >= widthofelement) {element.style.right = (scrollbarwidthadjustment) + "px";}
else {}
EDIT 2:
Fix for image resized smaller than its original size:
var offsetwidth = element.offsetWidth;
var widthadjustment = offsetwidth - scrollbarwidth; /* Get full width of image when scrollbar hidden, and then remove the scrollbar width. */
if(window1 < widthofelement && scrollbarwidth > 0) {
element.style.width = widthadjustment + "px";
element.style.right = (scrollbarwidthadjustment) + "px";
}
And then this code when showing the Y-scrollbar again:
if(window1 < widthofelement && scrollbarwidth > 0) {
element.style.width = "OriginalSizepx";
element.style.right = "0px";
}
If you want to use every edit that I have added, here is the full code:
/* First 5 lines for finding the scrollbar width. */
var $outer = $('<div>').css({visibility: 'hidden', width: 100, overflow: 'scroll'}).appendTo('body'),
widthWithScroll = $('<div>').css({width: '100%'}).appendTo($outer).outerWidth();
$outer.remove();
var scrollbarwidth = 100 - widthWithScroll;
var scrollbarwidthadjustment = scrollbarwidth / 2; /* For centered elements, divide the scrollbar width by 2. */
var element = document.getElementById('element'); /* Put element ID into a variable for easier use, and consecutive uses without re-identifying it. */
var window1 = windowWidth + scrollbarwidth; /* Window width + scrollbar width. */
var offsetwidth = element.offsetWidth; /* Get exact element size in current window. Shows shown dimensions when the window is resized. */
var widthadjustment = offsetwidth - scrollbarwidth; /* Get full width of image when scrollbar hidden, and then remove the scrollbar width. */
if(window1 >= widthofelement) {element.style.right = (scrollbarwidthadjustment) + "px";} /* If current window is equal to or greater than element width... */
if(window1 < widthofelement && scrollbarwidth > 0) { /* If current windows is smaller than the element width, and the window has a scrollbar greater than 0 pixels in width. */
element.style.width = widthadjustment + "px";
element.style.right = (scrollbarwidthadjustment) + "px";
}
/* When re-enabling the Y-scrollbar again; */
if(window1 >= widthofelement) {element.style.right = "0px";}
if(window1 < widthofelement && scrollbarwidth > 0) {
element.style.width = "OriginalSizepx";
element.style.right = "0px";
}
For further clarification, this code will prevent elements from jumping to the right when you hide the vertical scrollbar.
padding is your answer, as Shikkediel said. Just change margin to that and it'll work.
The items move because you change the default margin body has, so the whole body moves to the left (in case we are modifying margin-right).
If you remove the scroll bar, the default margin will go right behind it, and then you need to "buffer" the rest, left of the margin, and that's what padding does.
I really enjoy working with the Inspecting tool Chrome supplies (Ctrl + Shift + I) and then in the Styles tab on the right scorll down until you see the measurements. It really helps understand the CSS box model.
Did you add 'px' here..
$('body').css('margin-right', scrollbarwidth+'px')??
Just nowI tried in w3schools. If you add 'px' to above syntax, it is working for me.

Resize images with Javascript to fit them within the viewport

I'm calling an API that returns a URL to an image, the image could be any size and it's completely random.
I'm trying to resize images to fit within the page, ensuring the content is not pushed below the fold, or that the image doesn't hit the width of the page.
I've written some Javascript below, I've been testing it and am getting some strange results - the console logs are saying that the image is one size, but the element selector in Chrome's dev tools is usually saying something completely different. I'm sure I've made some basic mistake in my code, if you could take a look that would be great.
Javascript sets viewport height and width, checks if a photo src is available. Once the image has loaded, it checks if the natural dimensions are greater than that of the viewport, if so it attempts to resize - this is where the script is failing.
//check viewport
var viewportWidth = getWidth();
var viewportHeight = getHeight();
//get the media
if (data[2] == "photo") {
var tweetImage = document.getElementById("tweetImage");
//when it loads check the size against the browser size
tweetImage.onload = function () {
console.log('image height: ' + tweetImage.naturalHeight);
console.log('viewport height: ' + viewportHeight);
//does it matter if its landscape?
if (viewportWidth - tweetImage.naturalWidth < 1) {
tweetImage.width = Math.floor(tweetImage.naturalWidth - (viewportWidth - tweetImage.naturalWidth) * 1.2);
console.log('w');
} else if (Math.floor(viewportHeight - tweetImage.naturalHeight) < 1) {
console.log('h');
console.log(viewportHeight - tweetImage.naturalHeight);
console.log('changed result: ' + Math.floor(tweetImage.naturalHeight - (Math.abs(viewportHeight - tweetImage.naturalHeight))));
tweetImage.height = Math.floor(tweetImage.naturalHeight - (Math.abs(viewportHeight - tweetImage.naturalHeight)*1.2));
} else {
tweetImage.height = Math.floor(viewportHeight / 2);
}
tweetImage.align = "center";
tweetImage.paddingBottom = "10px";
};
//tweetImage.height = Math.floor(viewportHeight / 2);
tweetImage.src = data[3];
}
One option would be to use a CSS-based solution like viewport height units.
.example {
height: 50vh; // 50% of viewport height
}
See http://web-design-weekly.com/2014/11/18/viewport-units-vw-vh-vmin-vmax/

"full-window" slideshow image stretching bug

If you go to the slideshow I am working on here, you can see that the image resizes and moves correctly if you resize the browser window.
...unless you make the browser window's width smaller than a certain amount (i can't tell what defines that amount) and then it stretches the image instead of scaling it. How can I fix this?
Here is my resize code:
winWidth = $(window).width();
winHeight = $(window).height();
ratio = winWidth/winHeight;
if(ratio > imgRatio){
$('#curImg img').css({width:winWidth});
imgWidth = winWidth;
imgHeight = $('#curImg img').height();
$("#curImg img").css({top: (-1*Math.round((imgHeight-winHeight)/2)) + "px"});
$("#curImg").css({height: winHeight + "px"});
}else{
$('#curImg img').css({height:winHeight});
imgHeight = winHeight;
imgWidth = $('#curImg img').width();
$("#curImg img").css({left: (-1*Math.round((imgWidth-winWidth)/2)) + "px"});
$("#curImg").css({width: winWidth + "px"});
}
You could also check out this jQuery plugin:
http://srobbin.com/jquery-plugins/backstretch/
Or CSS tricks which looks at multiple solutions:
http://css-tricks.com/perfect-full-page-background-image/
You should take a look to tha background-size properties, especially at the cover values
Something I wrote that works:
//oWidth - container width
//oHeight - container height
//iWidth = image width
//iHeight = image height
iRatio = iWidth/iHeight;
wRatio = oWidth/oHeight;
if(iRatio<wRatio){
imageWidth = oWidth;
imageHeight = Math.ceil(iHeight*(oWidth/iWidth));
}
else{
imageHeight = oHeight;
imageWidth = Math.ceil(iWidth*(oHeight/iHeight));
}
$('#backgroundResizeImage').css({
'height': imageHeight,
'width': imageWidth
});
Hope this helps!
I rewrote your example a bit to make a self-contained demonstration.
Two notes unrelated to your question.
Make sure to cache any of your jQuery objects. You don't want to fetch items repeatedly, as that comes with an unnecessary performance cost.
My example shows this happening in the resize event for the window - I'm not sure how you had yours set up. For production, it's very important to throttle events bound to things like the window resize event, since they can be fired as fast as a browser can manage, which can lead to bad consequences. See this excellent article by John Resig on a time this bit Twitter in the ass.
The biggest relevant change is that I altered the way it's setting the heights and widths of images depending on how their ratio compares to the window. I think this way is a little clearer, but that's subjective. But it does work!
http://jsfiddle.net/L4k3s/2/
var $window = $(window),
$img = $('img'),
imgRatio = $img.width() / $img.height();
$window.on('resize', function (event) {
var imgWidth = $img.width(),
imgHeight = $img.height(),
winWidth = $window.width(),
winHeight = $window.height(),
ratio = winWidth / winHeight;
// The image is wider than the window
if (ratio < imgRatio) {
$img.width(winWidth);
$img.height(winWidth / imgRatio);
$img.css({
left: 0,
top: (-1 * Math.round((imgHeight - winHeight) / 2)) + "px"
});
// The image is taller than the window
} else {
$img.width(winHeight * imgRatio);
$img.height(winHeight);
$img.css({
left: (-1 * Math.round((imgWidth - winWidth) / 2)) + "px",
top: 0
});
}
});
​

WP7 - How to vertically center a div inside a webbrowser with javascript

I tried this on the WP7 forums and got nothing...
I am generating a rather simple html document, with all of its contents in a div. I need to vertically center that div in a webbrowser control. The usual approach of an outer div with "display: table" and an inner div with "display: table-cell" doesn't work in WP7-IE, so I went with javascript. This very simple js function works on desktop browsers:
function setContent() {
var windowHeight = document.documentElement.clientHeight;
if (windowHeight > 0) {
var contentElement = document.getElementsByClassName('DivToCenter')[0];
var contentHeight = contentElement.offsetHeight;
if (windowHeight - contentHeight > 0) {
contentElement.style.position = 'relative';
contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2)) + 'px';
window.external.Notify('' + ((windowHeight / 2) - (contentHeight / 2)));
}
else {
contentElement.style.position = 'static';
}
}
}
window.onload = function() {
setContent();
}
window.onresize = function() {
setContent();
}
The result of this function is that the div appears too low in the webbrowser control, as if the viewport had a greater height than it actually does. I pulled the size of the viewport out of the javascript, and noticed that its identical to the WebBrowser.ActualHeight property. So, my working hypothesis right now is that the size of the viewport reported to the javascript is in xaml logical pixels, which messes up the arithmetic. Thats my best theory about what's hapenning.
You should probably take a look at a post like this one: http://blogs.msdn.com/b/iemobile/archive/2011/01/21/managing-the-browser-viewport-in-windows-phone-7.aspx, which discusses the viewport size in WP7.

Categories

Resources