Responsive height for div element - javascript

I have this code for a responsive banner
.mybanner {
height:320px;
background:url(../img/banner.png) no-repeat;
background-size:100%;
}
responsive image background works fine, the only problem is .mybanner container's height is not changing
for example when i test with big screen
mybanner div element width = 980px
mybanner div element height = 320px
bakcground_image width = 980px
background_image height = 320px
but when i resized screen, let say width mybanner div element become 680px
mybanner div element width = 680px
mybanner div element height = 320px
bakcground_image width = 680px
background_image height = 220px
from that example there is different value mybannder height with background_image height, so it's become ugly white space
I already tried to modify it like this, to make .mybanner height became auto
.mybanner {
min-height:170px;
max-height:320px;
background:url(../img/banner.png) no-repeat;
background-size:100%;
}
or this:
.mybanner {
height:100%;
//height:auto;
background:url(../img/banner.png) no-repeat;
background-size:100%;
}
but not work....
any idea how to make height of div .mybanner change too depending on image size on his background

You can use javascript to change height.
<body onresize="resizediv()">
<div class="mybanner" id="mybanner">
...
<script>
function resizediv() {
div = document.getElementById('mybanner');
var imageSrc = div.style.backgroundImage.replace(/url\((['"])?(.*?)\1\)/gi, '$2').split(',')[0];
var image = new Image();
image.src = imageSrc;
var width = image.width,
height = image.height;
div.style.height = image.height;
}
</script>
Or There are all background size valid properties, you can chose best one:
http://www.w3schools.com/cssref/playit.asp?filename=playcss_background-size&preval=contain
Or simple don't use background, put the IMG to the div as a object and set image width 100% don't edit div and image height, it will compute automatically.

Related

Change div size base on javascript window.resize if innerWidth < 1300

I'm trying to create some responsive elements based on the innerWidth of the client browser.
For example if the innerWidth is less than 1300px I want the div to increase in size, else I want it to hold it's initial CSS value.
I've tried the code below which actively tracks the client innerWidth size but does not change the element when the specific value is reached.
I'm essentially trying to incorporate responsive elements at certain breakpoints.
function clientWidth(){
// Get the dimensions of the viewport
var width = window.innerWidth;
console.log(width);
};
var widthResult = clientWidth();
window.onresize = clientWidth;
var row1_col_3 = document.getElementById('row1_col_3');
if(widthResult < 1300){
row1_col_3.style.width = "450px";
} else{
row1_col_3.style.width = "300px";
};
You should be using CSS Media Queries for this, not JavaScript.
Run the snippet below and then click the "Full page" link at the top, right of the snippet window. You will see the background color change from yellow to green (assuming your screen is at least 1300px wide).
/* Default style */
div {
background-color:yellow;
width:250px;
}
/* Style for when viewport is at least 1300px wide */
#media screen and (min-width: 1300px) {
div {
background-color:green;
width:750px;
}
}
<div>Hello</div>

How to resize of a image base on screen size

How can I resize of a image base on screen size. Example:
I have a tag (width:1349, height: 449) and a image in div (width:78, height:78). When display image in div I fix for width of image is 60 and height is 60. I saw in mobile screen then the size of image still keep state so now I want to image display automatic resize base on screen example: in iPhone 4 the image have size (20x20) or percent of it in the screen. How can I use the formular for calculate it? This is my code jquery for calculate it.
var mw = $("#c").width();
var mh = $("#c").height();
console.log();
var img = new Image();
img.src = './img/photo-circle.png';
var wdImg = img.width;
var hiImg = img.height;
var ratioImg = wdImg/hiImg;
var ratioDiv = mw/mh;
if (ratioDiv > 1) {
var newwd = wdImg*(mh/hiImg);
alert(newwd);
} ;
You should be using percentages to achieve dynamic resizing of your elements. Then, as long as the parents are also dynamically resizing, their children will as well. For example, width: 30%; instead of width: 100px;
use the css unit vh and vw
each unit is worth 1% of the screen size
http://caniuse.com/#feat=viewport-units
example:
.item {
height: 20vw;
width: 20vw;
}
If the screen width is 100pixels, .item would be 20px by 20px
Simply you can use a bootstrap class called "img-responsive" at your img tag .
That's all , It will be responsive on any screen.

jQuery - resizing image to fit div [duplicate]

This question already has answers here:
Resize an image to fit in div
(5 answers)
Closed 9 years ago.
I have divs varying in height and width and wish for my images to be automatically resized to fill these divs 100%, and then of course centred.
At the moment my images are set to width 100% and then using the jQuery below centred, but this only works for images where the height are more than the div once resized.. how would I make it 100% for both height and width and center also.. completely filling the div (even if this means stretching the image)!
Thanks.
$('img.shelf-img').each(function(i, item) {
var img_height = $(item).height();
var top_margin = -(img_height / 2);
$(item).css({
'top': '50%',
'margin-top': top_margin
});
});
Use CSS to set both the Width and Height of the image to 100% and the image will be automatically stretched to fill the containing div, without the need for jquery.
Also, you will not need to center the image as it will already be stretched to fill the div (centered with zero margins).
HTML:
<div id="containingDiv">
<img src="">
</div>
CSS:
#containingDiv{
width: 200px;
height: 100px;
}
#containingDiv img{
width: 100%;
height: 100%;
}
That way, if your users have javascript disabled, the image will still be stretched to fill the entire div width/height.
OR
The JQuery way (SHRINK/STRETCH TO FIT - INCLUDES WHITESPACE):
$('img.shelf-img').each(function(i, item) {
var img_height = $(item).height();
var div_height = $(item).parent().height();
if(img_height<div_height){
//IMAGE IS SHORTER THAN CONTAINER HEIGHT - CENTER IT VERTICALLY
var newMargin = (div_height-img_height)/2+'px';
$(item).css({'margin-top': newMargin });
}else if(img_height>div_height){
//IMAGE IS GREATER THAN CONTAINER HEIGHT - REDUCE HEIGHT TO CONTAINER MAX - SET WIDTH TO AUTO
$(item).css({'width': 'auto', 'height': '100%'});
//CENTER IT HORIZONTALLY
var img_width = $(item).width();
var div_width = $(item).parent().width();
var newMargin = (div_width-img_width)/2+'px';
$(item).css({'margin-left': newMargin});
}
});
The JQuery way - CROP TO FIT (NO WHITESPACE):
$('img.shelf-img').each(function(i, item) {
var img_height = $(item).height();
var div_height = $(item).parent().height();
if(img_height<div_height){
//INCREASE HEIGHT OF IMAGE TO MATCH CONTAINER
$(item).css({'width': 'auto', 'height': div_height });
//GET THE NEW WIDTH AFTER RESIZE
var img_width = $(item).width();
//GET THE PARENT WIDTH
var div_width = $(item).parent().width();
//GET THE NEW HORIZONTAL MARGIN
var newMargin = (div_width-img_width)/2+'px';
//SET THE NEW HORIZONTAL MARGIN (EXCESS IMAGE WIDTH IS CROPPED)
$(item).css({'margin-left': newMargin });
}else{
//CENTER IT VERTICALLY (EXCESS IMAGE HEIGHT IS CROPPED)
var newMargin = (div_height-img_height)/2+'px';
$(item).css({'margin-top': newMargin});
}
});
If you want to keep the image ratio, I would set max-height and max-width to 100%. Here's a sample to show how that works. That will effectively shrink images that are larger than the div, but it will keep the aspect ratio.
For images that are smaller than the div, you will have to scale up with JavaScript. The basic algorithm is like so:
Find the aspect ratio of the image (width / height)
Find the aspect ratio of the div (width / height)
If the image's aspect ratio is less than the div's, set the image's height to 100%
If the image's aspect ratio is greater than the div's, set the image's width to 100%
Whichever dimension is not set, set it to auto
Obviously, you could use this algorithm for scaling up or down, but if you can be guaranteed that your div will always be smaller than your image, you can use the simpler CSS solution.
It looks like you've got code to do centering, so I'll leave that to you.

Retrieve size of background image after scaling with jQuery?

I have the following simple code to get me the background-image dimensions, but it grabs the size of the original image, not the scaled one I have in my div. I want to get pixel dimensions after scaling, is there any way to do that?
var actualImage = new Image();
actualImage.src = $("#chBox").css('background-image').replace(/"/g, "").replace(/url\(|\)$/ig, "");
actualImage.onload = function () {
width = this.width;
height = this.height;
}
EDIT:
The CSS to scale the background-image:
#chBox {
height:100%;
width:100%;
background-repeat:no-repeat;
background-image: url(../content/frog/1.jpg);
background-position: center;
-webkit-background-size: contain; /*for webKit*/
-moz-background-size: contain; /*Mozilla*/
-o-background-size: contain; /*opera*/
background-size: contain; /*generic*/
}
Instead of getting the dimensions of the actual image, you need to get the $('#someImage').css('width') and $('#someImage').css('height') of the image you want.
edit:
#someImage img {
width: 100px;
height: auto;
}
<td id="image">
<img id="someImage" src="image.jpg">
<script type="text/javascript">
alert($('#someImage').css('width'));
</script>
</td>
the code above would alert "100px". and of course if you use some jQuery to change the width of the image, like $('#someImage').css('width','300px'), the code would the update and alert "300px"
The code is doing what you're telling it to do. I don't believe there is a way to grab the 'scaled' size.
Alright, thanks to everyone for their responses but I thought of a bit of a workaround. I would like to see this feature in a later release of jQuery (grabbing scaled width, height) but with some math, it ain't so bad.
Essentially,
// create a fake image and load the original from background-img src
var actualImage = new Image();
actualImage.src = $("#chBox").css('background-image').replace(/"/g,"").replace(/url\(|\)$/ig, "");
actualImage.onload = function() {
// get original values
var origWidth = this.width;
var origHeight = this.height;
var width = 0;
var height = 0;
// need to bump it 140px as it seems the div's left comes from the super-container
var bump = 140;
// if the image is fat rather than tall,
if(origWidth > origHeight){
// set width for description to width of bg-img container
var width = $("#chBox").width();
// set left
$(".description").css("left", bump);
// calculate height and set bottom
height = (width * origHeight) / origWidth;
var blankSpace = $("#chBox").height() - height;
$(".description").css("bottom", (blankSpace/2));
} else {
// if image is tall,
var height = $("#chBox").height();
// calculate width
width = (height * origWidth) / origHeight;
// set left
var setLeft = $("#chBox").width();
$(".description").css("left", (setLeft/2) - 58); //wtf, 58?
// set bottom to 0
$(".description").css("bottom", 0)
}
$(".description").width(width);
}
There's quite a bit of site-specific stuff there, but basically I ran some algebra to find the proportions of the image. If it's a fat image rather than a tall image, the width of the container is the scaled width. The height is equal to the scaled width * original image height divided by the original image width. For some reason (and if someone could help with this I'd be grateful) the margin: 0 auto; property of my CSS doesn't work when you change up the div width, so I had to manually center it.

How do I get dynamically fluid images depending on browser window aspect ratio?

This might not be a simple question, but I try my best.
I have this example site: http://lotvonen.tumblr.com/
I have a little piece of javascript that automatically calculates the height of the inner browser window and sets that number as image wrapper div's height. Height of the image inside the wrapper is 100% of the wrapper, so that I get nice, full screen images on all normal screen sizes.
This works wonderfully on screens that are more wide than tall (desktops, laptops, etc).
But!
With screens that are more tall than wide (smartphones, iPads etc), the images get clipped from sides. I don't want that, so I have a temporary solution to have media query assigning height to auto and width to 100%, when browser screen max-width is 1024, so that no clipping occurs. But it's not a very good solution, and breaks at certain resolutions. It also destroys my JS with lower resolutions (eg. 800x600).
Here's the JS:
<script type="text/javascript">
var elems = document.getElementsByClassName('img'),
size = elems.length;
for (var i = 0; i < size; i++) {
var img = elems[i];
var height = (window.innerHeight) ? window.innerHeight: document.documentElement.clientHeight;
img.style.height=(height)+'px';
}
</script>
and here's my CSS:
.img {
max-width:100%
}
.img img {
width:auto;
}
.img img {
height:100%;
}
#media only screen and (max-width: 1024px) {
.img {
height:auto !important;
}
.img img {
height:auto !important;
max-width:100%;
}
and here's the div:
<li><div class="img"><img src="{PhotoURL-HighRes}" alt="{PhotoAlt}"/></div>
How do I get it so, that when the browser window is more tall than wide (eg. 720x1024), the images adjust by width, and when the browser window is more wide than tall (eg. 1024x720) the images adjust like they do now (by height, with the JS).
Is this possible at all? Is there a simple CSS fix to this or do I need to mess more with JS?
Thanks in advance!
You could also get the aspect in javascript on a regular basis and then add a class to the body object that would specify if it was 4:3, widescreen, or portrait. Then make it run on an interval in case the window changes size.
Example
CSS
.43 img { width: auto; }
.widescreen img { width: 100%; }
.portrait img { height: 100%; }
JavaScript
var getAspect = function(){
var h = window.innerHeight;
var w = window.innerWidth;
var aspect = w / h;
var 43 = 4 / 3;
var cssClass = "";
if (aspect > 43) {
cssClass = "widescreen";
}
else if (aspect === 43) {
cssClass = "43";
}
else {
cssClass = "portrait";
}
$("body").addClass(cssClass); // Using jQuery here, but it can be done without it
};
var checkAspect = setInterval(getAspect, 2000);
I would suggest getting the aspect ratio first in javascript. Use window.innerHeight and windows.innerWidth, and make the necessary division. Then, make this a condition. When the screen in wider than its height, set the image in css to width: 100%. Otherwise, set height: 100%.

Categories

Resources