How can i make my script center img in div - javascript

I have concocted a little script here out of bits and pieces I have found and scraped together, but I need a little help to add an extra function to it,
First of all - this is what it is doing for me at the moment:
It resizes and crops/letterboxes an image to completely fill a div
which is a % height and a % width – it keeps doing this whenever and
whatever window resize
It keeps working seamlessly as the window is resized
The image is filling 100% the area the div covers - left to right
and top to bottom.
The image is not being squashed or stretched - just being cropped
or is overflowing.
The image is kept as small as possible, so whatever the resize -
you can still see either the very sides OR the very top and bottom of
the image.
It seems to be OK across IE9, Fire Fox, Oprea, Chrome, and Safari
over XP and 7
All of these things are very important to me, please don't tell me that all i need is:
<img style="width : 100%;">
This is so much more than that. It's not too easy to explain but check the demo and drag the corner of the window around and that'll be worth 1000 words...!
Now, what I want to add:
All it is, I’d like the letter box to centre on the image.
When the div is a very tall portrait or a very flat landscape I’m just getting the top or just the left hand side of the image.
I’d like the centre of the original image to stay in the centre of the resized div.
I’ve tried a few things but have drawn a blank. I’m sure the script could feed a minus top: or left: into the style but it seems if I get too many div’s in div’s IE doesn’t like it, or what am I doing wrong?
Thing is I don’t really know how to wright this stuff, I only steal bit and bobs and splat them together…
And finally the demo
And the script:
<html>
<head>
<title>test</title>
<style>
#imgarea {
position:absolute;
right:0px;
height:75%;
width:70%;
top:25%;
}
</style>
<script type="text/javascript">
function resizeImage()
{
var window_height = document.body.clientHeight
var window_width = document.body.clientWidth
var image_width = document.images[0].width
var image_height = document.images[0].height
var area_width = window_width * 0.7
var area_height = window_height * 0.75
var height_ratio = image_height / area_height
var width_ratio = image_width / area_width
if (height_ratio > width_ratio)
{
document.images[0].style.width = "100%"
document.images[0].style.height = "auto"
}
else
{
document.images[0].style.width = "auto"
document.images[0].style.height = "100%"
}
}
</script>
</head>
<body onresize="resizeImage()">
<div id="imgarea">
<img onload="resizeImage()" src="f/a.jpg">
</div>
</body>
</html>
Thanks Very Much For This.

I'm not quiet sure if that's what you're looking for, but let's try this:
*upd: the wysiwyg is not working on comments at this moment, so sorry for messy code snippets.
1.Position the div#imgarea relatively. You can then float it to the right, to replicate your right:0px declaration. Don't forget to hide the overflow, to ensure that 'letter-boxed' parts of the image stay hidden.
#imgarea {
position: relative;
width: 70%;
height: 75%;
float: right;
overflow: hidden;
top: 25%;
};
Some user agents will add paddings and margins to the body element, thus preventing the image container to slide all the way to the right. Reset those, to get rid of the gaps between the container and the edge of the browser window.
body {
margin: 0;
padding: 0;
}
As for the image itself, position it absolutely.
img {
position: absolute;
}
And finally javascript. To center the image, you need to calculate what this width/height=auto sums up to, and then reset left/top attributes respectively. Your if function needs to be adjusted just a bit; leave your variables as is:
if (height_ratio > width_ratio) {
var newWidth, newHeight, newTop;
newWidth = area_width;
newHeight = image_height/width_ratio;
newTop = -(newHeight-area_height)/2;
document.images[0].style.width = newWidth;
document.images[0].style.height = newHeight;
document.images[0].style.top = newTop;
document.images[0].style.left = 0;
}else{
var newWidth, newHeight, newLeft;
newHeight = area_height;
newWidth = image_width/height_ratio;
newLeft = -(width-area_width)/2;
document.images[0].style.width = newWidth;
document.images[0].style.height = newHeight;
document.images[0].style.top = 0;
document.images[0].style.left = newLeft;
}
I hope that if this doesn't solve the issue completely, it at least sends you in the right direction. Good luck.

I'm not sure if this will work exactly, but may get your started. I had a client request a radial gradient be fixed to the left and right of a website's main ontent section. The page was set up with dynamic widths and I had a heck of a time getting one solid image to work, so I came up with a quick css solution.
#bgHold #gradLeft{
width:248px;
height:975px;
position:fixed;
right:50%;
margin-right:399px;
background:url("../images/gradLeft.png") top center no-repeat;
}
margin-right is half of the content block's width. So basically, the gradient is fixed on the page at 50% from the right, then shoved left 50% of the content box making it line up with the edge of the content. The same idea applies to the other side.
Now, with your situation, perhaps you can set right:50%; and margin-right:imgWidth/2?

Related

Proportionally scale website to fit browser window

What would be an elegant solution to proportionally scale and center an entire website to fit a browser window (and updating as it's re-sized)
Assume the base layout is 720x500px
Content should proportionally scale to fit, and then re-center.
Essentially, operating like this Flash plugin: http://site-old.greensock.com/autofitarea/ (though base size is known)
Site will contain several different types of elements in that 720x500 area... ideal solution would just scale the whole thing, not needing to style each individual element (in case it matters- images will be SVG and so scaling should have no negative affect on resolution)
Depending on the browsers you need to support (IE9+), you could achieve that with simple CSS transform.
See an example (using jQuery) in this jsfiddle
var $win = $(window);
var $lay = $('#layout');
var baseSize = {
w: 720,
h: 500
}
function updateScale() {
var ww = $win.width();
var wh = $win.height();
var newScale = 1;
// compare ratios
if(ww/wh < baseSize.w/baseSize.h) { // tall ratio
newScale = ww / baseSize.w;
} else { // wide ratio
newScale = wh / baseSize.h;
}
$lay.css('transform', 'scale(' + newScale + ',' + newScale + ')');
console.log(newScale);
}
$(window).resize(updateScale);
If you need backwards compatibility, you could size everything in your site with % or em, and use a similar javascript to control the scale. I think that would be very laborious though.
One solution I'm using is working with a container in which I put an iframe that's being resized to fit as much available screen as possible without losing it's ratio. It works well but it's not completely flexible: you need to set dimensions in your content page in % if you want it to work. But if you can manage your page this way, I think it does pretty much what you want.
It goes like this. You create a container html page that's basically only styles, the resize script and the iframe call. And you content goes into the iframe page.
<style>
html, body
{
border: 0px;margin: 0px;
padding:0px;
}
iframe
{
display: block;
border: 0px;
margin: 0px auto;
padding:0px;
}
</style>
<script>
$(document).ready(function(e){
onResizeFn();
});
$(window).resize(function(e){
onResizeFn();
});
// this stretches the content iframe always either to max height or max width
function onResizeFn(){
var screen_ratio = 0.70 // this is your 720x500 ratio
if((window.innerHeight/window.innerWidth) > screen_ratio){
var theWidth = window.innerWidth
var theHeight = (window.innerWidth*screen_ratio);
} else {
var theHeight = window.innerHeight;
var theWidth = (window.innerHeight/screen_ratio);
}
document.getElementById("your_iframe").width = theWidth + "px"
document.getElementById("your_iframe").height = theHeight + "px"
}
</script>
// And then you call your page here
<iframe id='your_iframe' src='your_content_page' scrolling='no' frameborder='0'"></iframe>

Keeping a fixed div a specific distance from another div even when resized

I basically want the navigation div to be say 50px from the right edge of the picture but it needs to be fixed so that when you scroll it still remains at the location. Basically, as the image gets resized with the browser, the nav should keep a permanent relation of 50px to the image. I'm just not sure how to go about doing this with a fixed div.
#wrapperNav {
position: fixed;
top: 45%;
bottom: 0;
right: 200px;
z-index:999;
}
Code: http://jsfiddle.net/LLtnZ/
Calculate the position of the nav on window resize.
JS
$(window).resize(function(){
var gutter_space = 55;
var left_pos = ($('.item img').outerWidth() + $('.item img').offset().left) - gutter_space;
$('#wrapperNav').css('left',left_pos);
})
Use left position instead of right.
DEMO
UPDATE: Equal spacing
JS
$(window).resize(function(){
var left_width = ($('.item img').outerWidth() + $('.item img').offset().left);
var gap = ($(window).outerWidth() - left_width);
var right_pos = (gap - $('#wrapperNav').width())/2; //Space to be left on each side of the nav.
$('#wrapperNav').css('right',right_pos);
});
Also update your css, for demo purpose gave width to the #wrapperNav
Updated Demo
I'm not 100% sure I understood the question, but I took a crack at it. Is this similar to what you were asking?
http://jsfiddle.net/LLtnZ/1/
var moveNav = function(left){
$('#wrapperNav').css({'left': left});
};
moveNav( $('.item:visible').width() + 50 );
$(window).on('resize', function(left){
var img = $('.item:visible');
var imgWidth = img.width();
moveNav(imgWidth + 50);
});
Hope this helps! Let me know if thats headed in the right direction.

JavaScript: Get window width minus scrollbar width

Ok, I thought this would be really simple, but it's turning out not to be. I think I'm just messing something up in my HTML/CSS, but here goes.
I have a basic page like so:
HTML
<!DOCTYPE html>
<html>
<head>
<link href='test2.css' rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="test2.js"></script>
</head>
<body>
<div id="scroll"></div>
</body>
</html>
test2.css
* {
padding: 0;
margin: 0;
}
html, body {
height: 100%;
width: 100%;
}
#scroll {
height: 100%;
width: 100%;
overflow: scroll;
background-color: black;
}
test2.js
$(document).ready(function() {
// my resolution is 1440x900
alert('innerwidth should be 1425');
// all of these return 1440
alert('body innerwidth: ' + $('body').innerWidth());
alert('document width: ' + $(document).width());
alert('window width: ' + $(window).width());
alert('scroll div innerwidth: ' + $('#scroll').innerWidth());
alert('document.documentElement.clientWidth: ' + document.documentElement.clientWidth);
alert('document.documentElement.scrollWidth: ' + document.documentElement.scrollWidth);
});
So I've got one element on the page... a div that takes up the entire screen, or rather it should be taking up the entire screen minus the scrollbars. Now, I've been doing some snooping on how to grab the width and height of a page without the scrollbars, but unfortunately, none of them return the proper value... which makes me believe I'm missing the boat in my HTML or CSS.
I looked at the following:
jquery - how to get screen width without scrollbar?
how to get the browser window size without the scroll bars
So what I need is for a method to return the value of my viewable screen minus the respective scrollbar value... so for my width, my value should be 1425 because the scrollbar is 15 pixels wide. I thought that's what innerWidth's job was, but apparently I'm wrong?
Can anyone provide any insight? (I'm running Firefox 24.)
EDIT
To add some background, I've got a blank page. I will be adding elements one by one to this page, and I need to use the width of the page when calculating the sizes for these elements. Eventually, this page will grow and grow until the scrollbar appears, which is why I'm trying to force the scrollbar there from the start, but apparently, that still doesn't do anything.
EDIT2
Here's something even more interesting... if I do document.getElementById('scroll').clientWidth, I get the proper innerWidth, but if I do $('#scroll').width() or $('#scroll').innerWidth(), they both return the max resolution... sounds like a jQuery bug.
I got this somewhere and would give credit if I knew where, but this has been succesfull for me. I added the result as padding when setting the html overflow to hidden.
Problem is that the scrollbar is a feature of the browser and not the web page self. Measurement should be done dynamically. A measurement with a scrollbar and a measurement without a scrollbar will resolve into calculating the difference in width.
Found the source: http://www.fleegix.org/articles/2006/05/30/getting-the-scrollbar-width-in-pixels
scrollCompensate = function () {
var inner = document.createElement('p');
inner.style.width = "100%";
inner.style.height = "200px";
var outer = document.createElement('div');
outer.style.position = "absolute";
outer.style.top = "0px";
outer.style.left = "0px";
outer.style.visibility = "hidden";
outer.style.width = "200px";
outer.style.height = "150px";
outer.style.overflow = "hidden";
outer.appendChild(inner);
document.body.appendChild(outer);
var w1 = inner.offsetWidth;
outer.style.overflow = 'scroll';
var w2 = inner.offsetWidth;
if (w1 == w2) w2 = outer.clientWidth;
document.body.removeChild(outer);
return (w1 - w2);
}
var htmlpadding = scrollCompensate();
The correct answer is in this post marked as accepted:
CSS media queries and JavaScript window width do not match
This is the correct code:
function viewport() {
var e = window, a = 'inner';
if (!('innerWidth' in window )) {
a = 'client';
e = document.documentElement || document.body;
}
return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}
Discovered a very hacky solution... by adding this before my alerts in test2.js, I get the proper width:
var p = $('body').append('<p style="height: 100%; width: 100%;"></p>');
alert(p.width());
$('body').remove('p');
And consequently, all of the alerts now have the proper width. I also don't even need overflow-y in the CSS if I do it this way. Curious why this solves it...
The real answer should be keeping the HTML and CSS as is, then using document.getElementById('scroll').clientWidth. Using clientWidth gets the viewable area minus the scrollbar width.
The correct width of the page is given by $(document).width().
Your problem is that you're using a scroll within the div (overflow: scroll).
Using $(document).width() the returned value is already discounting the visible width of the scroll, but how do you put a scroll within the div value returned is no longer the same.
As the width of the scroll is not standard and varies from system to system and browser to browser, it is difficult to solve.
I suggest you remove the scroll of the div and let the browser manage this by default in the body, then yes you have the correct width.

Re-sizing the webpage content

In my project I have a webpage which has 2 div areas right and left. The left div takes almost 60% of the whole page width and the right one takes around 36% of the page. I wanted to resize the both div areas in a proper ratio when I shrink the browser from the right side or left side. The UI is getting generated from Javascript. This is the code.
boardHolderPadding = $board.outerHeight() - $board.height();
$board.height(viewportHeight - siblingsHeight - boardHolderPadding);
this.$('#board .droptarget').setWidthAsRatioOfHeight(this.options.ratio);
$('#sidebar').width($(window).width() - $board.find('#board').width() - 50);
I tried with JQuery resize plugin but couldnt get the proper result I'm looking for. Anyone have suggestion?
Thanks
See jsfiddle example but I think you just need to set your widths as percentages rather than trying to calculate them - note display is set to inline-block
<div>
<div class="small-left-column">this is the left column</div>
<div class="large-right-column">this is the right column</div>
</div>
<style>
.small-left-column {
width: 30%;
background-color: #aeaeae;
display: inline-block;
}
.large-right-column {
width: 60%;
background-color: #aeaeae;
display: inline-block;
}
</style>
So I think for your example your would have something like this
$(document).ready(function () {
$('#sidebar').addClass('small-left-column');
$('#board').addClass('large-right-column');
});
Maybe you're looking for the pure-Javascript version of the above:
$(document).ready(function () {
$('#sidebar').css( {
width: '30%'
backgroundColor: '#aeaeae',
display: 'inline-block'
});
$('#board').css({
width: '60%',
backgroundColor: '#aeaeae',
display: 'inline-block'
});
});
I did it in a different way in Javascript and I hope this will help someone to fix if they come across an issue like that
relativeSize : function(width, height){
var boardWidth = this.$("#board").width(),
boardHeight = this.$("#board").height(),
newcard = this.$("#newCard").width(),
space = width - boardWidth - newcard;
ratio = space / width * 3; //used to increment the ratio with 3 as the ratio is very tiny value, this will help to increase minimizing size
bheight = boardHeight - 25; // used to reduce the height by 25px, u can use any amount to match ur ratio
var relHeight = (space < ratio) ? bheight : height;
return relHeight;
}
Thanks

How to resize an image that has a gradient according to the current page height?

I am using an image as the background for my site. It has a black/white gradient, and is 1px wide.
The CSS:
background-image:url('../image/gradient.png');
which makes it repeat itself. The height of the image is 2000px.
Is it possible to change the height of the image dynamically, so it fits all page sizes: If the height of a page is less than 2000px, the height of the image should be smaller, if the height of the page is bigger, the image should be bigger.
Thanks in advance
I have tried various in-browser gradient techniques, and they dont seem to work the same on all browsers.
I usually approach this problem in one of two ways.
If you can use CSS3, then use CSS gradients (I always find http://colorzilla.com/gradient-editor/ a good choice to play about with gradients), you can then set this to be 100% height of the window.
If CSS3 isn't an option, i usually just pick a height, say 500px, and make a gradient for that. Then, since gradients typically go from colour A to colour B, just set the underlying background colour to match colour B and the gradient will work similarly on all monitors.
Assuming a gradient going from blue to black:
body {
/* ensure body always fills viewport */
min-height: 100%;
/*gradient fades to black so set underlying BG to black*/
background: url(/path/to/gradient.gif) repeat-x #000;
}
}
Maybe am not getting the right context of your question, but this can be do it easily with somethin like
#SomeImg.src {
width: 100%;
position: absolute;
top: 0;
left: 0;
}
Resize this page to see it action: http://css-tricks.com/examples/ImageToBackgroundImage/
With CSS3 you can use background-size: cover and there are some other techniques discussed here.
You could create several images with varying heights and dynamically match the closest image size. If you do this you'd need to tie into the window.resize event to update the image if the user resizes the window.
window.onload = setBackgroundImage;
window.onresize = setBackgroundImage;
function setBackgroundImage() {
var winH = 500;
if (document.body && document.body.offsetWidth) {
winH = document.body.offsetHeight;
} else if (document.compatMode=='CSS1Compat' && document.documentElement && document.documentElement.offsetWidth ) {
winH = document.documentElement.offsetHeight;
} else if (window.innerWidth && window.innerHeight) {
winH = window.innerHeight;
}
if (winH > 400) {
document.body.style.backgroundImage = "url('../image/gradient800px.png')";
} else if (winH > 800) {
document.body.style.backgroundImage = "url('../image/gradient1000px.png')";
} else if (winH > 1000) {
document.body.style.backgroundImage = "url('../image/gradient1500px.png')";
} else if (winH > 1500) {
document.body.style.backgroundImage = "url('../image/gradient2000px.png')";
} else {
document.body.style.backgroundImage = "url('../image/gradient400px.png')";
}
}
I don't think the solution is very pretty, but it should work.

Categories

Resources