If statement works on resize, not ready? - javascript

I am trying to accomplish two things:
The main content div will be dynamically sized to fit the exact height of the window. I accomplish that goal with this function:
$(document).on( 'ready', function() {
panelsResize();
$(window).on( 'resize', panelsResize );
});
function panelsResize() {
var screenHeight = $(window).height();
var screenWidth = $(window).width();
if (screenWidth > 768) {
$( ".panels" ).css( "height", screenHeight );
}
};
The class .panels is applied to the main content area.
This works swell.
I am trying to fill the .panels with the images in.large. These images need to retain aspect ratio while being scalable. I have based my code on this answer.
This works, but not on ready. I have to resize the screen, dropping below the media query that switches the display for .large to none. When I resize to the higher media query, switching display to block, the functionality works perfect.
Any ideas?
Here's the function (and markup):
$(document).on( 'ready', function() {
bgResize();
$(window).on( 'resize', bgResize );
});
function bgResize(){
$( '.large' ).each(function() {
var th = $(window).height(),//box height
tw = $(window).width(),//box width
im = $(this).children('img'),//image
ih = im.height(),//inital image height
iw = im.width();//initial image width
if ( iw < tw ) {
im.css( { "width" : "100%", "height" : "auto" } );
}
else if ( ih < th ) {
im.css( { "height" : "100%", "width" : "auto" } );
}
var nh = im.height(),//new image height
nw = im.width(),//new image width
hd = (nh-th)/2,//half dif img/box height
wd = (nw-tw)/2;//half dif img/box width
if (nh<nw) {
im.css({marginLeft: '-'+wd+'px', marginTop: 0});//offset left
} else {
im.css({marginTop: '-'+hd+'px', marginLeft: 0});//offset top
}
});
};
This is the HTML:
<ul id="homePanels">
<li id="cat1" class="panels">
<div class="large">
<img src="#" alt="" />
</div>
<div class="small">
<img src="#" alt="" />
</div>
</li>
</ul>
The CSS:
#homePanels {
list-style: none;
margin:0;
padding:0;
overflow: hidden;
}
.large {
width:100%;
height:100%;
}
#media (min-width: 768px) {
.large{display: block;}
.small{display:none}
}
#media (max-width: 768px) {
.small {display:block;}
.large {display:none;}
}

i think it will work if you use jQuery ready() function.
$(document).ready(function() {
bgResize();
$(window).on('resize', bgResize );
});

You just need to change
$(document).on( 'ready', function()
for
$(document).ready( function()

Thanks! I made the change to the ready event.
I realized that using the image's width and height were causing the issue, since I was grabbing, basically, two 0s. So, since I knew the aspect ratio of the images, I used that to scale the images on screen resize.
var screenHeight = $(window).height(),
screenWidth = $(window).width(),
aspectRatio = 0.57066014669927,
screenAspectRatio = screenHeight / screenWidth;
if ( screenAspectRatio < aspectRatio ){
$("img").css({"width" : "100%" , "height" : "auto"});
} else if ( screenAspectRatio > aspectRatio ){
$("img").css({"width" : "auto" , "height" : "100%"});
}
But it's solved now. Thanks for your help!

Related

jQuery UI : My resize function is not working properly

I want to know that my resize function is not working properly as I aspected means the problem is when I resize the div ( increase the padding ) and leave it and when I again try to resize it padding shrinks.
Note : I am Increasing the padding not the height.
$( function() {
$( "#resizable" ).resizable({
resize: function( event, ui ) {
var originalHeight = ui.originalSize.height;
var newHeight = ui.size.height;
var pad = 5;
if (originalHeight < newHeight) {
pad = newHeight - originalHeight;
}
$(this).css({'padding': pad, 'height': 200, 'width': 400});
}
});
});
My fiddle link
Yeah #Botimoo seems correct. You should probably consider positioning with something other than padding. But something like this probably is close to what you want if you want to stick with padding
https://jsfiddle.net/6rh7emog/5/
<div id="resizable" class="ui-widget-content">
<div id="wrapper">
<h3 class="ui-widget-header">Resizable</h3>
</div>
$( function() {
$( "#resizable" ).resizable({
aspectRatio: true,
resize: function( event, ui ) {
var originalHeight = ui.originalSize.height;
var newHeight = ui.size.height;
$('#wrapper').css({
'padding': newHeight - 200
});
}
});
});

How to center container on resize using onWindowResize

I'm using a script that is resizing my .container when my window is resized. This is my page: http://cjehost.com/qt/nipt/page6.php
If you resize the browser window, you'll see the container resize but not stay centered. Is there a way to center my container? Here is my script:
// Resize the map to fit within the boundaries provided
function resize(maxWidth, maxHeight) {
var image = $('img'),
imgWidth = image.width(),
imgHeight = image.height(),
newWidth = 0,
newHeight = 0;
if (imgWidth / maxWidth > imgHeight / maxHeight) {
newWidth = maxWidth;
} else {
newHeight = maxHeight;
}
image.mapster('resize', newWidth, newHeight, resizeTime);
}
// Track window resizing events, but only actually call the map resize when the
// window isn't being resized any more
function onWindowResize() {
var curWidth = $(window).width(),
curHeight = $(window).height(),
checking = false;
if (checking) {
return;
}
checking = true;
window.setTimeout(function() {
var newWidth = $(window).width(),
newHeight = $(window).height();
if (newWidth === curWidth &&
newHeight === curHeight) {
resize(newWidth, newHeight);
}
checking = false;
}, resizeDelay);
}
$(window).bind('resize', onWindowResize);
My css:
.container {margin:0 auto;}
I would recommend really a CSS approach instead of JavaScript approach for this one. Responsive CSS with #media queries are there for this. Don't use DOM Manipulations with JavaScripts, that are really costly in the terms of performance.
CSS Centering
.parent {
position: relative;
}
.child {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
#media Queries
#media screen and (max-width: 380px) {
// Styles for Mobiles
}
#media screen and (min-width: 381px) and (max-width: 760px) {
// Styles for Tablets
}
#media screen and (min-width: 761px) {
// Styles for Desktops
}
You can find an exhaustive list online.
I managed to make this work by replacing window with .container (my container div). It's still a bit clunky - i.e. when I switch to full screen from smaller resolutions the container doesn't always resize. Here is my working code:
// Track window resizing events, but only actually call the map resize when the
// window isn't being resized any more
function onWindowResize() {
var curWidth = $('.container').width(),
curHeight = $('.container').height(),
checking = false;
if (checking) {
return;
}
checking = true;
window.setTimeout(function() {
var newWidth = $('.container').width(),
newHeight = $('.container').height();
if (newWidth === curWidth &&
newHeight === curHeight) {
resize(newWidth, newHeight);
}
checking = false;
}, resizeDelay);
}
$(window).bind('resize', onWindowResize);
$(window).resize(onWindowResize);
});
Here is a working fiddle: enter link description here
I found reference to this approach and fiddle here: enter link description here
Thanks to #LBF

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.

jQuery resize of images [duplicate]

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.

Change jQuery slider option dynamically based on window width

I would like to change a jQuery option based on window width (on load as well as on resize).
I've found solutions close to what I need, but I don't understand jQuery or javascript enough to customize them for my needs.
Here's my jQuery code:
<script type="text/javascript">
var tpj = jQuery;
tpj.noConflict();
tpj(document).ready(function () {
if (tpj.fn.cssOriginal != undefined) tpj.fn.css = tpj.fn.cssOriginal;
tpj('#rev_slider_1_1').show().revolution({
delay: 5000,
startwidth: 1920,
startheight: 515,
hideThumbs: 200,
thumbWidth: 100,
thumbHeight: 50,
thumbAmount: 4,
navigationType: "bullet",
navigationArrows: "verticalcentered",
navigationStyle: "navbar",
touchenabled: "on",
onHoverStop: "off",
navOffsetHorizontal: 0,
navOffsetVertical: 20,
shadow: 0,
fullWidth: "on"
});
}); //ready
</script>
I want to change the startheight based on window width.
If the window width is above 1280 I would like the value for the height to be 515, and if it is below 1280 I would like the height to be 615 and if the width is less than 480 make the height 715.
With help from another post I am able to change the css I need using this script:
$(window).on('load resize', function () {
var w = $(window).width();
$("#rev_slider_1_1 #rev_slider_1_1_wrapper")
.css('max-height', w > 1280 ? 515 : w > 480 ? 615 : 715);
});
But I need to also change the jQuery startheight value on the fly.
Why don't you use percentages in CSS.
I created an example here:
http://jsfiddle.net/webwarrior/aLJQm/52/
<div id="slider"></div>
Css:
#slider {
width: 90%;
}
to resize, use JavaScript with something like this on your resize:
var clientWidth = jQuery(window).width();
var clientHeight = jQuery(window).height();
jQuery("#rev_slider_1_1 #rev_slider_1_1_wrapper").height(clientHeight/20);
Trying the following now on images:
.slotholder{
overflow: hidden;
}
.slotholder img{
width: 110%;
margin-left: -5%;
}
as on http://jsfiddle.net/webwarrior/wLFEJ/11/
hth
Modify the 'load resize' event binding like so:
$(window).on('load resize', function () {
var w = $(window).width();
$("#rev_slider_1_1 #rev_slider_1_1_wrapper")
.css('max-height', w > 1280 ? 515 : w > 480 ? 615 : 715);
if(w > 1280) { tpj('#rev_slider_1_1').revolution('option', 'startheight', 515);}
else if(w < 1280 && w > 480) { tpj('#rev_slider_1_1').revolution('option', 'startheight', 615); }
else { tpj('#rev_slider_1_1').revolution('option', 'startheight', 715); }
});
This would work for most jquery plugins, but since you seem to be using a paid plugin (http://codecanyon.net/item/slider-revolution-responsive-jquery-plugin/2580848 would be my guess), the customization might be restricted - so, All the Best! :)

Categories