jQuery resize of images [duplicate] - javascript

This question already has answers here:
Image resize of items jQuery
(2 answers)
Closed 10 years ago.
I have managed to fit automatically the images of the gallery per row depending if it´s horizontal (one image per row) or vertical (two images per row).
The problem now is that I want the images to be scalable (resize on window resize) but I have no idea how to achieve it. How it should me made? (I'm looking for a javascript/jquery solution to avoid height: auto problems...)
This is the web: http://ldlocal.web44.net/test2/gallery.html
Can be downloaded here: http://ldlocal.web44.net/test2/test.zip
this is my code:
var gallery = new Gallery($('#gallery_images_inner'));
function Gallery(selector){
this.add_module = function(type, image){
var container = $('<div />' , {
'class' : 'gallery_container'
}).append(image);
if(type == 'horizontal'){
var h_ar = image.attr('height') / image.attr('width');
container.css({
'width' : selector.width(),
'height' : selector.width()*h_ar
})
}
if(type == 'vertical'){
container.css({
'width' : v_width,
'height' : v_height
})
}
container.appendTo(selector);
container.children('img').fitToBox();
}
var _this = this;
var gutter = 0;
// start vars for counting on vertical images
var v_counter = 0;
var w_pxls = 0;
var h_pxls = 0;
// iterates through images looking for verticals
selector.children('img').each(function(){
if($(this).attr('width') < $(this).attr('height')){
v_counter++;
h_pxls += $(this).attr('height');
w_pxls += $(this).attr('width');
}
})
// calculates average ar for vertical images (anything outside from aspect ratio will be croped)
var h_avrg = Math.floor(h_pxls/v_counter);
var w_avrg = Math.floor(w_pxls/v_counter);
var v_ar = h_avrg/w_avrg;
var v_width = (selector.width())/2;
var v_height = v_width*v_ar;
selector.children('img').each(function(){
if(parseInt($(this).attr('width')) > parseInt($(this).attr('height'))){
_this.add_module('horizontal', $(this));
}else{
_this.add_module('vertical', $(this));
}
})
selector.isotope({
masonry: {
columnWidth: selector.width() / 2
}
});
}

Update ALL NEW CODE:
http://jsfiddle.net/vYGGN/
HTML:
<div id="content">
<img class="fluidimage" src="http://thedoghousediaries.com/comics/uncategorized/2011-04-06-1b32832.png"
/>
</div>
CSS:
body {
text-align:center;
}
img {
float: right;
margin: 0px 10px 10px 10px;
}
#content {
width:70%;
margin: 0px auto;
text-align: left;
}
JS:
$(document).ready(function () {
function imageresize() {
var contentwidth = $('#content').width();
if ((contentwidth) < '300') {
$('.fluidimage').attr('height', '300px');
} else {
$('.fluidimage').attr('height', '600px');
}
}
imageresize(); //Triggers when document first loads
$(window).bind("resize", function () { //Adjusts image when browser resized
imageresize();
});
});
Found this at this article:
http://buildinternet.com/2009/07/quick-tip-resizing-images-based-on-browser-window-size/

If you want to resize images automatically and scale them down proportionally, all you have to do is set a css max-width on the <img> tag. You can scale it down automatically with a percentage value according to the $(window) or any element in the document. Here's an example of how to scale it proportionally using the $(window) to a percentage of the window:
$(document).ready(function() {
$(window).resize(function() {
var xWidth = $(window).width();
$('.[img class]').each(function() {
$(this).css({maxWidth: xWidth * ([your percentage value of window] / 100)});
});
}).trigger('resize');
});
Change [img class] to the class of the images.
Change [your percentage value of window] to the percent of the window element you want your images width to be scaled at. So, if you want 90%, change this to 90. When the user resizes the browser window, it will automatically resize the images accordingly as well.

Related

Cornerstone image viewer Resize canvas size onclick button

Am using Cornerstone Image viewer.
I want to split the screen into 3 columns.
Initially left and right side div should hide and middle div should full window size display.
when i click show left div screen has to reduce and fit into 2 div's.
When i click show right div hide left and show with right and middle div's.
function resizeStudyViewer() {
var studyRow = $(studyViewer).find('.studyContainer')[0];
var height = $(studyRow).height();
var width = $(studyRow).width();
$(seriesList).height("100%");
$(parentDiv).width(width - $(studyViewer).find('.thumbnailSelector:eq(0)').width());
$(parentDiv).css({ height: '100%' });
$(imageViewerElement).css({ height: $(parentDiv).height() - $(parentDiv).find('.text-center1:eq(0)').height() });
$(imageViewerElement).css({ height: '100%'});
imageViewer.forEachElement(function (el, vp) {
cornerstone.resize(el, true);
if ($(el).data('waiting')) {
var ol = vp.find('.overlay-text');
if (ol.length < 1) {
ol = $('<div class="overlay overlay-text">Please drag a stack onto here to view images.</div>').appendTo(vp);
}
var ow = vp.width() / 2, oh = vp.height() / 2;
ol.css({ top: oh, left: ow - (ol.width() / 2) });
}
});
}
// Call resize viewer on window resize
$(window).resize(function () {
resizeStudyViewer();
});

whay can't I change both image height and width at same time with javascript?

I have an image in a div and I want the image to stay centered at all times.
If the width of the image is wider than the screen, then I want the image to expand to the width of the view port. And if the image is shorter than the height of the view port then I want it to expand to the height of the view port.
In my code, when I expand the width, the height expands automatically, which is great since I don't have to calculate it. The height does the same thing. When the height is expanded, the width stays proportional.
However, if the width changes in such a way that the height is now smaller than then view port, then I need to check the height and bring it back up to the view port height (which should expand the width again but it doesn't). When I have to change both height and width at the same time, the automatic proportioning doesn't work. If I do one or the other, it does work.
How can I accomplish this so they can both be changed and work without distorting the image?
my code:
inner_width = $(window).innerWidth();
inner_height = $(window).innerHeight();
if (inner_width < original_pic_width ) {
$(pic).css({'width': original_pic_width});
}
else {
$(pic).css({'width' : inner_width });
}
if (inner_height < original_pic_height){
$(pic).css({'height': original_pic_height});
}
else {
$(pic).css({'height' : inner_height });
}
CSS contain is pretty nice.
$("div").css({
backgroundImage: "url(" + $("img").prop('src') + ")",
backgroundSize:"contain",
backgroundRepeat: "no-repeat"
});
div { width:200px; height:200px; border:1px solid red;}
div img { display:none }
<div>
<img src="http://www.somebodymarketing.com/wp-content/uploads/2013/05/Stock-Dock-House.jpg"/>
</div>
<script src="https://code.jquery.com/jquery-2.2.3.min.js"
integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo="
crossorigin="anonymous"></script>
Here is a possible solution (not sure to understand clearly what you want though). Note that I'm not absolutely sure that the centering method is cross-browser.
var div = $("div");
var img = $("img");
var imgw = img.width();
var imgh = img.height();
var imgr = imgw / imgh;
var sizes = [300, 120];
var i = 0;
setInterval(function () {
div.width(sizes[i]);
i = (i + 1) % 2;
adjust();
}, 1000);
function adjust () {
var divw = div.width();
var divh = div.height();
var divr = divw / divh;
if (divr < imgr) {
img.width("100%");
img.height("auto");
} else {
img.width("auto");
img.height("100%");
}
}
div {
position: relative;
}
img {
display: block;
position: absolute;
top: 0; bottom: 0;
right: 0; left: 0;
margin: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width:120px;height:120px;border:10px solid #5900CC;">
<img style="width:100%;" src="http://i.stack.imgur.com/jKXi2.jpg" />
</div>
If you set both height and width... both dimensions, height and width will be set.
It should be enough to set just one dimension if you set the width=viewport's width if it's horizontal (width>height) or the height=viewport's height if it's vertical.
Find which dimension you have to change and change that one only. You can do that by checking the difference between the image's width and the window's innderWidth, and the difference between the image's height and the window's innerHeight. Whichever difference is greater is the one you need to change only. That should take care of the other dimension without having to resize both.

Set height to element dynamically and change height on window resizes using jQuery

I am working on a project where I need to set the height dynamically, means when the page loads the height must be set to itself and it's a responsive box, so when the browser window resizes the height increases but I am unable to fix it. I shared the script below. It's not something to calculate with window height or else, it should set and change the height based on window resizes. Any help?
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
var itemHeight = $('.item').height();
$('.item').each(function() {
$(this).css({
height: itemHeight + 'px'
});
});
$(window).on('resize', function(event) {
$('.item').each(function() {
$(this).css({
height: itemHeight + 'px'
});
});
});
Please see the jsfiddle:
https://jsfiddle.net/rj1xy1ue/
I will suggest you to use % instead of px. px will fix the value, but % will automatically compute the values based on the available viewport.
var itemHeight = 20; //Sample value
$('.item').each(function () {
$(this).css({
height: itemHeight + '%'
});
});
Simply, find the perfect value of itemHeight which is ideal for your case and then assign it. No need for extra resize event handler.
In your current code, in resize event you are assigning same value again which doesn't make any difference to the dimension. Hence you are not able to see the difference on resize.
Try this:
var itemHeight = $('.item').height();
function resizer() {
$('.item').each(function () {
$(this).css({
height: itemHeight + 'px'
});
});
}
$(window).on('resize', function (event) {
itemHeight = 350 //any different value
resizer();
});
Sample Demo: http://jsfiddle.net/lotusgodkk/GCu2D/822/
Note: Make sure you change the value of itemHeight in resize handler
What you are describing is called Responsive design.
A key idea in responsive design is to use percentages in place of px.
See these references:
WebDesignerWall on Responsive Design
CSS-Tricks question
for some ideas.
Note that using percentages for height is not as important as for width. You might also want to check out
Responsive Layouts with flexbox
On the jQuery side, you can use something like this:
var win = $(window);
$(function() {
win_size_recalc();
$(window).on('resize', function(){
win_size_recalc();
});
}); //end document.ready
function win_size_recalc(){
ww = win.width();
//EXAMPLE OF USE:
if (ww <= 550){
$('#header').css({'height':'50px'});
$('nav').css({'height':'55px'});
$('#headerstuff').css({'width':'98%'});
}else if (ww <= 650){
$('#headerstuff').css({'width':'98%'});
$('nav').css({'width':'98%'});
}else if (ww <= 770){
$('#headerstuff').css({'width':'90%'});
$('nav').css({'width':'90%'});
}else if (ww <= 850){
$('#headerstuff').css({'width':'90%'});
$('nav').css({'width':'90%'});
}else if (ww <= 900){
//etc etc
}
You might also want to check out CSS media queries, which is the CSS way of doing what we just did above using jQuery:
https://css-tricks.com/css-media-queries/
https://css-tricks.com/snippets/css/media-queries-for-standard-devices/
and more
I am not sure if I am able to understand your question correctly but I'll give a try based on what I could understand anyway.
You want the .item objects to resize on resize event of window object such that you want to start with whatever .height() these .item objects have, and then scale proportionally to the window height on resize.
If this is what you wanted, the solution is pretty simple. You calculate the difference in .height() of window object, and you add (or remove) that difference to the default .height() of .item objects.
Take a look at this jsFiddle and resize the height of the result panel to observe the difference in height of the .item objects. And tell me if this is what you were expecting the result to be.
The JavaScript used in the example is as below:
var items = $('.item');
var windowObject = $(window);
var defaultWinHeight = windowObject.height();
var defaultItemHeight = items.height();
items.css({ height: defaultItemHeight + 'px' });
windowObject.on('resize', function (event) {
var currWinHeight = windowObject.height();
var difference = currWinHeight - defaultWinHeight;
var itemHeight = defaultItemHeight + difference;
items.css({ height: itemHeight + 'px' });
});
Apologies if this is not what you were looking for. Hope it helps in some way though.
Update #1:
And here is another resulting jsFiddle of the same experiment but involving calculating percentages.
JavaScript:
var items = $('.item');
var windowObject = $(window);
var defaultWinHeight = windowObject.height();
var defaultItemHeight = items.height();
items.css({ height: defaultItemHeight + 'px' });
windowObject.on('resize', function (event) {
var currWinHeight = windowObject.height();
var currWinPercent = (currWinHeight/defaultWinHeight)*100;
var itemHeight = (currWinPercent/100)*defaultItemHeight;
items.css({ height: itemHeight + 'px' });
});
As others have noted, the main problem is you're only calculating itemHeight once. This fiddle shows a more modern way to use jQuery to achieve your goals (use on instead of bind):
http://jsfiddle.net/sean9999/7j4sz3wv/6/
$(function(){
"use strict";
var resizeBoxes = function(){
var padding = 25;
var parentHeight = $('body').height() - padding;
$('#debug').html( 'parent height = ' + parentHeight );
$('.item').css('height',parentHeight);
};
$(window).on('resize',resizeBoxes);
resizeBoxes();
});
body {
position: absolute;
height: 100%;
width: 100%;
margin: 0;
padding: 0;
background-color: #FED;
}
#debug {
width: 50%;
float: right;
height: 100%;
margin-top: 25%;
font-weight: bold;
color: navy;
}
.item {
min-width: 25px;
border: 2px solid blue;
background-color: silver;
min-height: 100px;
float: left;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div id="debug"></div>

How can I create a click and drag to change the width of an object with jQuery?

I have an object that I want to change the width of when you click on it and drag right or left. Adding to the width or taking away from it as you move the mouse (or finger).
<style>
#changeMe {width:300px; height: 200px;}
</style>
<div id="changeMe">
Some Content
</div>
<script>
$('#changeMe').mousedown(function(){
//Some Code?????
});
</script>
What you want to do is track the x co-ords of the mouse. If greater than they were before, increase size, if lower, decrease the size.
Not tested but the below should be inspiration.
var oldXPos = 0;
var isDragging = false;
$(document).mousemove(function(event) {
if (isDragging)
{
var difference = event.pageX - oldXPos;
// Do something with this value, will be an int related to how much it's moved
// ie $('#changeMe').css.width += difference;
}
oldXPos = event.pageX;
});
$('#changeMe').mousedown(function() {
isDragging = true;
})
$('#changeMe').mouseup(function() {
isDragging = false;
})
You just need a resizable({}) effect .
$('#changeMe').resizable({});
You can look at this article
Resizable
$(function() {
$('.testSubject').resizable();
});
or
#changeMe {width:300px; height: 200px; border: 1px solid black;}
<body>
<div id="changeMe">
Some Content
</div>
</body>
$('#changeMe').resizable({});
Or
$(function(){
$('img[src*=small]').toggle(
function() {
$(this).attr('src',
$(this).attr('src').replace(/small/,'medium'));
},
function() {
$(this).attr('src',
$(this).attr('src').replace(/medium/,'large'));
},
function() {
$(this).attr('src',
$(this).attr('src').replace(/large/,'small'));
}
);
});
If I understand your question correctly, that you want to be able to dynamically increase/decrease the size of the object as it moves along the x-axis, I recommend that you use $('#changeMe').offset() inside the jQuery UI drag event.
You can create a formula that you want to use based on an initial offset, and the new offset to size your container by $('#changeMe').css({ width: X, height: Y });, and insert whatever your X and Y values are in pixels.
Edited for further elaboration with code:
var initX = 0;
var initW = 0;
$('#changeMe').draggable({
start: function() {
initX = $(this).offset().left;
initW = $(this).width();
},
drag: function() {
var deltaX = initX - $(this).offset().left;
$(this).css({ width: initW + deltaX });
}
});
If you used that as your base, it's a very nice and simple solution for your application.

jQuery Set Height of Element to Highest in the group

I'm trying to work with jQuery to find the highest element from the first 3 elements within a div then set all 3 the same height then check the next 3 and set them.. etc.. if my window width == X, also if the window width is < X then find the highest 2 elements then set them, then the next 2 then the next 2 etc.
This is my current code which works for all the elements, I would just like to to go through the elements in groups (2's and 3's) and set the height for that group based on the result and window size.
// Find highest element and set all the elements to this height.
$(document).ready(function () {
// Set options
var height = 0;
var element_search = "#cat_product_list #cat_list";
var element_set = "#cat_product_list #cat_list";
// Search through the elements set and see which is the highest.
$(element_search).each(function () {
if (height < $(this).height()) height = $(this).height();
//debug_(height,1);
});
// Set the height for the element(s if more than one).
$(element_set).each(function () {
$(element_set).css("height", (height+40) + "px");
});
});
Any help is much appreciated :)
Try this for setting all of them to the max height:
$(document).ready(function() {
var maxHeight = 0;
$("#cat_product_list #cat_list").each(function() {
if ($(this).outerHeight() > maxHeight) {
maxHeight = $(this).outerHeight();
}
}).height(maxHeight);
});
Update 22/09/16: You can also achieve the same thing without any Javascript, using CSS Flexbox. Setting the container element to have display: flex will automatically set the heights of the elements to be the same (following the highest one).
I've sorted this now,
Check out my Fiddle:
http://jsfiddle.net/rhope/zCdnV/
// Find highest element and set all the elements to this height.
$(document).ready(function () {
// If you windows width is less than this then do the following
var windowWidth = $(window).width();
if (windowWidth < 2000) {
var i = 0,
quotes = $("div#cat_product_list").children(),
group;
while ((group = quotes.slice(i, i += 2)).length) {
group.wrapAll('<div class="productWrap"></div>');
}
}
// Find the width of the window
var windowwidth = $(window).width();
//debug_(windowwidth);
// Set options
var height = 0;
var element_wrap = ".productWrap";
var element_search = ".cat_list";
// Search through the elements set and see which is the highest.
$(element_wrap).each(function () {
$(this).find(element_search).each(function () {
if (height < $(this).height()) height = $(this).height();
});
//alert("Block Height: " +height);
// Set the height for the element wrap.
$(this).css("height", (height) + "px");
// Unset height
height = 0;
});
});
Just to add another suggestion. Here is a jQuery plugin I wrote that accepts one parameter. You can call it like this:
$('.elementsToMatch').matchDimensions("height");
You can match the height, width or if no parameter is entered, both dimensions.
$(function() {
$(".matchMyHeight").matchDimensions("height");
});
(function($) {
$.fn.matchDimensions = function(dimension) {
var itemsToMatch = $(this),
maxHeight = 0,
maxWidth = 0;
if (itemsToMatch.length > 0) {
switch (dimension) {
case "height":
itemsToMatch.css("height", "auto").each(function() {
maxHeight = Math.max(maxHeight, $(this).height());
}).height(maxHeight);
break;
case "width":
itemsToMatch.css("width", "auto").each(function() {
maxWidth = Math.max(maxWidth, $(this).width());
}).width(maxWidth);
break;
default:
itemsToMatch.each(function() {
var thisItem = $(this);
maxHeight = Math.max(maxHeight, thisItem.height());
maxWidth = Math.max(maxWidth, thisItem.width());
});
itemsToMatch
.css({
"width": "auto",
"height": "auto"
})
.height(maxHeight)
.width(maxWidth);
break;
}
}
return itemsToMatch;
};
})(jQuery);
.matchMyHeight {background: #eee; float: left; width: 30%; margin-left: 1%; padding: 1%; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="matchMyHeight">
Div 1
</div>
<div class="matchMyHeight">
Div 2
</div>
<div class="matchMyHeight">
Div 6<br> Div 6<br> Div 6<br> Div 6
</div>
var highHeight = "0";
$(".item").each(function(){
var thHeight = $(this).height();
if(highHeight < thHeight ){
highHeight = thHeight;
}
});
console.log(highHeight)

Categories