Standardize image into div - javascript

I'm working with Bootstrap and I want to put some photos into my div and I want them to be all at the same size ("standardize").
If they're too big (and they will always be) I want to resize them to fit in my div and crop them if necessary.
For the moment her is what I do :
I've tried to change the style of the image in jQuery in a function:
• If the height is bigger than the width, I switch the style to max-width:100% and height auto.
• Inversement if the width is bigger than the height.
But I'm still new to jQuery and I am probably doing something wrong; can someone light my lantern please?
Here is my jQuery
$(document).ready(function(){
photoResize();
$(window).resize(function(){
photoResize();
});
});
function photoResize(){
image_w = $('img').width();
image_h = $('img').height();
if(image_h > image_w)
{
$('img').css("max-width","100%");
$('img').height("auto");
}
else if(image_w > image_h)
{
$('img').css("max-height","100%");
$('img').width("auto");
}
}
And here is a Fiddle for a better view : https://jsfiddle.net/Baldrani/DTcHh/9801/

Simplicity
I do this quite often in the CMS we use at work for galleries etc. The method I use involves a jQuery library called imgLiquid.js.
This will turn an inline image into a background image on the parent div. It's good because you can achieve your desired effect. It will crop the image (as it technically becomes a background image) and will apply background-size: cover; and background-position: center center; as inline styles.
You can find the plugin here
To initialize the plugin you just need:
$(".myele").imgLiquid();
Overheads
The plugin is very small (roughly around 5.106 KB) so you don't need to worry about adding weight to the page. It really it the most simple method I've come across (bar using thumbnails generated from the sever-side - see note at the bottom).
Cue CSS
I've tested this thoroughly and found it gives excellent results. You may then ask... what happens to my parent divs (as technically the plugin hides the img element - which therefore means the parent element doesn't know what height to make itself).
An easy method to make things work responsively, or not:
.myelement:before{
content: "";
padding-top: 50%;
display: block;
}
This CSS will give your heights back to the wrapping element. So if you wanted certain proportions you could use this math:
h / w * 100 = your percentage for the padding-top.
Working Example
Small note
Technically if I had the control I'd advise just using thumbnails.. I assume you're using some sort of system that could technically just render cut down versions of the images? The reason I use this method — and suggested it — is that I don't have control over the CMS and I'm assuming you just want to manage the code that's being produced as it's not stated.

if you want to make your images the same size then you dont need any javascript or calculations, why not just set it in css?
.someUniqueContainer img{
width:300px;
height:300px; // or what ever height you want
}
I'm guessing that in reality you actually want to crop all your images to a set width/height. if that's the case you'll need a serverside script for that.
where are the images coming from? it would be easyer to just edit them. if they are coming from a user then you would resize/crop on the server on file upload

There were several mistakes in your code.
Please look at this jsfiddle, please see https://jsfiddle.net/DTcHh/9796/
$(document).ready(function () {
photoResize();
$(window).resize(function () {
photoResize();
});
});
function photoResize() {
image_w = $('img').width();
image_h = $('img').height();
if (image_h > image_w) {
$('img').css("max-width", "100%");
$('img').height("auto");
} else if (image_w > image_h) {
$('img').css("max-height", "100%");
$('img').width("auto");
}
}

sth like this?, although this is pure css, not jquery included, might not be suit in your case..
body {
margin-top:20px
}
.col-xs-3 {
margin: 5px 0;
width: 500px;
height:120px
}
.col-xs-3 > div {
width: 100%;
height: 120px;
background-repeat: no-repeat;
background-position: center;
background-size: cover;
}
JsFiddle

Related

container should automatically adjust to the height of the background image for responsive design css only

I working on a responsive design.
If i load the image with the image tag i have no problem with the size, but then it will load on screen too even if i set display:none. This cause loading problems on smartphone devices...
This way i trying to scale it with background-size:contain, but the problem is i have to add an height for the container.
That means if i have a device with different width the image doesn´t fit more.The same problem with background-size:cover. The image flow over if i change width.
Would do it just with css, because there are many pictures and this cause loading problems with javascript.
#header {
width: 100%;
background-image:url(../images/backgrounds/Header_phone2.jpg);
background-size:contain;
background-repeat:no-repeat;
min-height: 200px;
}
Edit
My solution with JS in the answer, improvement tipps are welcome
I made now something, what is working nice for me.
I´m not really good with jquery, this way i´m looking forward for improvement tipps.
Html:
container in container ...
Css stay almost same:
#header {
height:auto;
}
#header-image{
width: 100%;
min-height: 155px;
background-image:url(../bilder/backgrounds/Header_phone2.jpg);
background-size:cover;
background-repeat:no-repeat;
}
Jquery:
if ($( window ).width() <= 966) {
var screenwidth = $(window).width();
var heightimage = (screenwidth /940) * 198;
$("#header-image").css("height", heightimage);
}
$(window).resize(function() {
if ($( window ).width() <= 966) {
var screenwidth = $(window).width();
var heightimage = (screenwidth /940) * 198;
$("#header-image").css("height", heightimage);
}
});
This is working fantastic !! Same like you add the image with img tag and the image doesn´t load with screen design. (look there)
If javascript disabled set min-heigth, like this the image is displayed too.
With jquery i calculate the height of the image. For this i take the width from the display, divide it trough image width and multiply it with height from image. => the correct height for the container.
With the windows-resize function you can change the size of the window and it still works.
This is very simple and works nice for me.
Click for Jsfiddle.
If you use the js script where you delete the src path from img tag, then it will send a request too. With this variant you don´t have problems, look out first link.
Some skilled guys could improve this: select the image width and height with jquery and make a function.

JS launches before CSS

This is currently happening in chrome, in firefox I haven't had this issue (yet).
Here is a VERY simplified version of my problem.
HTML:
<div class="thumbnail">
Click me!
</div>
CSS:
div {
width: 200px;
height: 300px;
background-color: purple;
}
a {
position: absolute;
}
#media (max-width: 991px) {
div {
height: 200px;
}
}
Javascript:
$(document).ready(function () {
var $parent = $('#clickMe').parent();
function resize() {
$('#clickMe').offset({
top: $parent.offset().top + $parent.height()-$('#clickMe').height()
});
}
$(window).on('resize', resize);
resize();
});
The problem:
So what does this give when I resize (without dragging)? Well javascript launches first and sets the position of the <a></a> , then CSS applies the height change if we are < 992 px.
Logically the button is now visually at the outside of the div and not on the border like I had originally defined it to be.
Temporary solution proposed in this post.
jQuery - how to wait for the 'end' of 'resize' event and only then perform an action?
var doit;
$(window).on('resize', function(){ clearTimeout(doit); doit = setTimeout(resize, 500); });
Temporary solution is not what I'm looking for:
However, in my situation I don't really need to only call 'resize' when the resizing event is actually done. I just want my javascript to run after the css is finished loading/ or finished with it's changes. And it just feels super slow using that function to 'randomely' run the JS when the css might be finished.
The question:
Is there a solution to this? Anyone know of a technique in js to wait till css is completely done applying the modifications during a resize?
Additional Information:
Testing this in jsfiddle will most likely not give you the same outcome as I. My css file has many lines, and I'am using Twitter Bootstrap. These two take up a lot of ressources, slowing down the css application (I think, tell me if I'm wrong).
Miljan Puzović - proposed a solution by loading css files via js, and then apply js changes when the js event on css ends.
I think that these simple three steps will achieve the intended behavior (please read it carefully: I also suggest to read more about the mentioned attributes to deeply understand how it works):
Responsive and fluid layout issues should always be primarily (if not scrictly) resolved with CSS.
So, remove all of your JavaScript code.
You have positioned the inner a#clickMe element absolutely.
This means that it will be positioned within its closest relatively positioned element. By the style provided, it will be positioned within the body element, since there is no position: relative; in any other element (the default position value is static). By the script provided, it seems that it should be positioned within its direct parent container. To do so, add position: relative; to the div.thumbnail element.
By the script you provided, it seems that you need to place the a#clickMe at the bottom of div.thumbnail.
Now that we are sure that the styles added to a#clickMe is relative to div.thumbnail, just add bottom: 0px; to the a#clickMe element and it will be positioned accordingly, independently of the height that its parent has. Note that this will automatically rearrange when the window is resized (with no script needed).
The final code will be like this (see fiddle here):
JS:
/* No script needed. */
CSS:
div {
width: 200px;
height: 300px;
background-color: purple;
position: relative; //added
}
a {
position: absolute;
bottom: 0px; //added
}
#media (max-width: 991px) {
div {
height: 200px;
}
}
If you still insist on media query change detection, see these links:
http://css-tricks.com/media-query-change-detection-in-javascript-through-css-animations/
http://css-tricks.com/enquire-js-media-query-callbacks-in-javascript/
http://tylergaw.com/articles/reacting-to-media-queries-in-javascript
http://davidwalsh.name/device-state-detection-css-media-queries-javascript
Twitter Bootstrap - how to detect when media queries starts
Bootstrap: Responsitive design - execute JS when window is resized from 980px to 979px
I like your temporary solution (I did that for a similar problem before, I don't think half a second is too long for a user to wait but perhaps it is for your needs...).
Here's an alternative that you most likely have thought of but I don't see it mentioned so here it is. Why not do it all through javascript and remove your #media (max-width.... from your css?
function resize() {
var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
if(width<992){
$("div").each(function(e,obj){$(obj).height(200);});
}
$('#clickMe').offset({
top: $parent.offset().top + $parent.height()-$('#clickMe').height()
});
}
In the html page, put the link to css file in head section; next, put the link to js file just before the /body tag and see what happens. In this way css will load always before js.
Hope this help you.
Did you try to bind the resize handler not to the window but to the object you want to listen to the resize ?
Instead of
$(window).on('resize', resize);
You can try
$("#clickMe").on('resize', resize);
Or maybe
$("#clickMe").parent().on('resize', resize);
var didResize = false;
$(window).resize(function() {
didResize = true;
});
setInterval(function() {
if (didResize) {
didResize = false;
console.log('resize');
}
}, 250);
I agree with falsarella on that you should try to use only CSS to do what you are trying to do.
Anyway, if you want to do something with JS after the CSS is applied, I think you can use requestAnimationFrame, but I couldn't test it myself because I wasn't able to reproduce the behavior you explain.
From the MDN doc:
The window.requestAnimationFrame() method tells the browser that you
wish to perform an animation and requests that the browser call a
specified function to update an animation before the next repaint. The
method takes as an argument a callback to be invoked before the
repaint.
I would try something like this:
var $parent = $('#clickMe').parent();
function resize(){
$('#clickMe').offset({
top: $parent.offset().top + $parent.height()-$('#clickMe').height()
});
}
window.onresize = function(e){
window.requestAnimationFrame(resize);
}
window.requestAnimationFrame(resize);
Anyone know of a technique to wait till css is completely done loading?
what about $(window).load(function() { /* ... */ } ?
(it executes the function only when the page is fully loaded, so after css loaded)

How do I resize/crop images simualar to how background-size:cover does?

I am building a responsive site using bootstrap 3 & I need a photo gallery on it. The client want to update the gallery themselves..
My issue is the images that they upload can be of any size & any proportion.. How can I make the image fit a certain size div?
Requirements (must work similar to background-size:cover):
-images must keep their original proportions (can be cropped to fit the div)
-images must be stretched/shrunk to fit the FULL div (no white space)
-image must be centered vertically & horizontally in the div
I know I can do something like this but I need it to work more like "background-size:cover":
.myImages {
height:300px;
width:300px;
overflow:hidden;
}
http://jsfiddle.net/w4xTN/1/
EXAMPLE:
You can see at the link below that I have used "background-image:cover" for the "featured properties" photos.. I need to do something similar for normal images (unless someone knows of an image gallery that will support "background-image:cover" for the images?):
http://new.amberlee.com.au/for-sale/browse-for-sales
NOTE: JQuery/Javasript is OK to use & resizing them on upload is not an option ;)
You've got your tag within the .myImages so you need to add properties for your tag hence:
.myImages > img {
height: 100%;
width: 100%;
}
If you want to center the img, just change the height or width attribute to "auto";
you could also hack the img tag to center vertically whereby the image is cropped with playing with the vertical margin:
e.g.
margin-top: -33%;
http://jsfiddle.net/denistsoi/rLmxL/1/
No, you can't get it quite like background-size:cover but..
This approach is pretty damn close: it uses javascript to determine if the image is long or tall and applies styles acordingly.
JS
$('.myImages img').load(function () {
var height = $(this).height();
var width = $(this).width();
console.log('widthandheight:', width, height);
if (width > height) {
$(this).addClass('wide-img');
}
else {
$(this).addClass('tall-img');
}
});
CSS
.tall-img{
margin-top:-50%;
width:100%;
}
.wide-img{
margin-left:-50%;
height:100%;
}
http://jsfiddle.net/b3PbT/
Edit: this is a shameless repost from your last question ;)

Turning scripts off and on based on Media Queries?

I am using a widget in my layout and I have it now so when a certain breakpoint is hit it will not display that larger widget and then goes to the smaller one. The larger widget does hide and the smaller one shows up but the text that is associated with both isn't right.
The text for the large widget displays and the smaller text for the small widget doesn't. I am pretty sure it has to do with the scripts each are using. The display none does hide the elements but the scripts seem to be still running.
I have absolutely no clue about JavaScript yet and would prefer a HTML or CSS answer if possible. If not then I will go with JS but will need some direction please. I have read numerous articles and even in the process of learning JS but still not sure how some of what I've read applies.
#media all and (max-width: 900px) {
// styles
}
if (document.documentElement.clientWidth < 900) {
// scripts
}
This is what I've found that seems like it is what I need but I'm not sure on the syntax of how to call the script I need. Do I just put the script itself in there without any other information? I have also read about using jquery to do this with something like this
$(window).resize(function() {
if ($(this).width() > 480) {
// call supersize method
}
});
And I've even read about using Modernizer to do this but I still have to go through the documentation.
In the bin it doesn't show any of the text at all but the larger text is there and off to the side of the small widget. I just need to shut that large script off and turn the other on at a certain media query.
Any help is greatly appreciated.
HTML
<aside class="smallScreen">
<div class="smallWeather" style='width: 200px; height: 440px; background-image:
url(http://vortex.accuweather.com/adcbin/netweather_v2/backgrounds/red_500x440_bg.jpg
); background-repeat: no-repeat; background-color: #993333;' ><div
id='NetweatherContainer' style='height: 420px;' ><script src='http://...'></script>
</div></div></aside>
</div></div></div></aside>
<aside class="largeScreen">
<div class="largeWeather" style='width: 500px; height: 440px; background-image:
url(http://vortex.accuweather.com/adcbin/netweather_v2/backgrounds/red_500x440_bg.jpg
); background-repeat: no-repeat; background-color: #993333;' ><div
id='NetweatherContainer' style='height: 420px;' ><script src='http://...'></script>
</div></div></aside>
CSS
#media screen and (min-width: 564px) and (max-width: 604px) {
.largeScreen {
display: none;
}
.smallScreen {
display: block;
width: 55%;
min-width: 240px;
height: 100%;
font-size: 0;
margin-left: auto;
margin-right: auto;
margin-bottom: 1.2rem;
}
.smallWeather {
position: relative;
display: block;
width: 240px;
height: 420px;
background: white;
margin-left: auto;
margin-right: auto;
}
What is the best way to do this and why please? Is jQuery the best way from a mobile performance standpoint?
UPDATE: Going to use enquire.js because of it's straightforward approach (although I'm still a bit sketchy on it's use) and how small it is.
This is the basic code:
enquire.register("screen and (max-width: 605px)", {
// OPTIONAL
// If supplied, triggered when a media query matches.
match : function() {},
// OPTIONAL
// If supplied, triggered when the media query transitions
// *from a matched state to an unmatched state*.
unmatch : function() {},
// OPTIONAL
// If supplied, triggered once, when the handler is registered.
setup : function() {},
// OPTIONAL, defaults to false
// If set to true, defers execution of the setup function
// until the first time the media query is matched
deferSetup : true,
// OPTIONAL
// If supplied, triggered when handler is unregistered.
// Place cleanup code here
destroy : function() {}
});
Still not done and looking for more support with this. Now that I've chose this route, I see that there is quite a few articles and questions already about enquire.js. I will update my situation as I read up.
UPDATE: This is where I'm at but it's not working yet. I have the styles associated with each script still in the HTML and display none used accordingly. Will doing this work once I get the enquire.js correct?
Here is the new jsbin
Thanks again for everything!!
I think you are looking for something like enquire.js, which is a lightweight JavaScript library for responding to CSS media queries.
If you don't want to use a library, this post on reacting to media queries in JavaScript runs through a way of doing what you are after with vanilla JavaScript.
Here's a jsFiddle Demo with some working example code, and here's a Fullscreen jsFiddle Demo, which is handy when trying to test how it works. If you use the fullscreen version and make the browser window less than 600px wide, a javascript alert will tell you that you have done so. Because the alert comes up, the browser will jump back to its original size and tell you that it got bigger than 600px again. So you can see, it calls the match function when it matches (so at the time of loading and at the time of resizing to a larger width), and it calls the unmatch function when resizing to a smaller width, because then the media query doesn't match any more. That's how you call a certain function only for mobile or only for desktop based on their screen size.
JS
enquire.register("screen and (min-width:600px)", {
match: function () {
alert("Now the screen width is more than 600px");
},
unmatch: function () {
alert("Now the screen width is less than 600px");
}
});

JQuery image slider having issue with image width & height

I am using image slider specified at: here
My images are of different sizes and I want to set the width and height of the image using following code:
<img src='77.png' width="20px" height="20px" />
But this doesnt work.
I am preety new to javascript, any help will be greatly approciated!
I really don't think this code can handle it (perhaps with a very serious overhaul of the javascript). I set up a fiddle here: http://jsfiddle.net/JLjCP/9/ and in examining what it is doing, it simply does not care what size the image itself is nor does it care if you have resized the image explicitly through the width and height properties. It is only taking the referenced image file and using it as a repositioned background image for the split components which are purely sized by the width and height of the display and the number of sections you tell it to do it in.
So the short answer is this code will not do what you want it to do.
put this in your css :
.cs-coin-slider
{
/*i think the class name is depend on what you set*/
-o-background-size: 20px 20px;
-webkit-background-size: 20px 20px;
-khtml-background-size: 20px 20px;
-moz-background-size: 20px 20px;
background-size: 20px 20px;
}
if you insist to use this coin-slider, no matter you set the size in html or set the css width+height of the image, it wont resized because this plugin treats the image as background..and that css3 background resize that is the only way that save you :)
The documentation on that page says that you can pass size options to the constructor:
$('#coin-slider').coinslider({ width: 20, height: 20 });
If you have different sized images in the same slideshow and you want to change the slider's size dynamically, it might not be possible. Use same sized images or tweak the CSS so that you get black bars around smaller images or something to that effect.
Please post your complete HTML/JS source code, the image size shouldn't matter as long as they are the same height/width as the container of the slideshow. Chances are you are possibly calling the plugin in the wrong way in your JS.

Categories