Change Div Width Along on load and resize - javascript

I wrote this code to change width and height of the wrapper box based on the available space on the screen. When I open the page, div loads well but when I resize it the size of the div does not change.
var width = (($(window).width()) - 100);
var height = (($(window).height()) - 100);
$(window).ready(function() {
$("#wrapper").width(width);
$("#wrapper").height(height);
});
$(window).resize(function(){
$("#wrapper").width(width);
$("#wrapper").height(height);
});
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Xyz</title>
</head>
<body>
<div id="wrapper">
asd
</div>
</body>
</html>

You need to recalculate the height and width variables within the event handlers:
$(window).ready(calculateSize);
$(window).resize(calculateSize);
function calculateSize() {
var width = $(window).width() - 100;
var height = $(window).height() - 100;
$("#wrapper").width(width);
$("#wrapper").height(height);
}
Note however, that this is possible in CSS alone:
#wrapper {
position: absolute;
top: 0;
left: 0;
right: 100px;
bottom: 100px;
}

You need to recalculate the dimension.
$( window ).resize(function(){
width = (($(window).width())-100);
height = (($(window).height())-100);
$("#wrapper").width( width );
$("#wrapper").height( height );
});

I use this function I wrote and it is working well:
//when I load the page
window.onload = function(event) { resizeDiv(); }
//when I resize the page
window.onresize = function(event) { resizeDiv(); }
function resizeDiv() {
vpw = $(window).width()-100;
vph = $(window).height()-100;
$('#wrapper').css({'height': vph + 'px'});
$('#wrapper').css({'width': vpw + 'px'});
}

Related

How can I move elements into view when the window is resized?

I have a project which I need to do an aquarium and the fishes inside gather on click.
I have done everything, but here is the problem, the program should work on resize.
What I am trying to say. If I resize the browser window, the fishes should re-appear in the visible spot of the window and continue swimming.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<style>
body{background-color:aqua; width:100%; height:100%;padding:0; margin:0;}
img{width:50px; height:50px;}
div{position:absolute;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
i = 0;
function swim(fishid){
newLeft = Math.random()*1200; // due to new width
newTop = Math.random()*600; //due to new height
do_move(fishid, newTop, newLeft, Math.random()*1000);
}
function do_move(fishid, topPos, leftPos, timeToMove=0){
$("#"+fishid).css({"transform": "rotateY(0deg)"});
ll = leftPos + 'px';
tt = topPos + 'px';
if( parseInt($("#"+fishid).css('left'))>leftPos){
$("#"+fishid).css({"transform": "rotateY(180deg)"});
}
$("#"+fishid).animate({"left": ll, "top": tt}, 1000+timeToMove, function(){swim(fishid);});
}
$(document).ready(function(){
let fishes = Math.random()*5+5;
for(i=0; i<fishes; i++){
$("body").append('<div id="fish'+ i + '"><img src="http://icons.iconarchive.com/icons/icons8/ios7/256/Animals-Fish-icon.png"></div>');
swim("fish" + i);
}
$("*").click(function(ev){
$("div").each(function(){
$(this).stop();
do_move($(this).attr("id"), ev.pageY-25, ev.pageX);
});
});
$ ( window ).resize(function(){});// I have to do it with this also
});
</script>
</head>
<body>
</body>
</html>
The resize event will be triggered whenever you resize your screen. You can easily get the screens inner width and height similarly.
$(window).resize(function(e){
console.log($(this).innerWidth())
console.log($(this).innerHeight())
});
Use the actual window dimensions instead of hard-coded values:
newLeft = Math.random() * window.innerWidth * 0.9;
newTop = Math.random() * window.innerHeight * 0.9;
No resize event handler is needed since the swim() function is called repeatedly. This means that there's a brief period where fish can escape the window, but it's resolved after one program cycle. Putting overflow: hidden on the body eliminates scrollbars during resize.
I've introduced an arbitrary reducer of 90% to allow for fish size. That could be adjusted.
Fiddle demo
newLeft = Math.random() *$( window ).width();
newTop = Math.random() *$( window ).height()
https://jsfiddle.net/rkv88/nh1buw8o/

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>

Setting <div> size to be the same as window?

I'm trying to use jQuery to set the height of a div so that it takes up the entire window + the height of a header (so that you can scroll the header off the page) but no more than that. I would think the height of the div would be the height of the window + the height of the header I'm trying to hide.
When I set the div to window height, however, it creates overflow. Here's the rough code:
var $body = $("#body"),
$container = $("#container"),
$window = $(window),
$content = $("#mainContent"),
$header = $("#header"),
bodyHeight = window.innerHeight + $header.height();
$body.css("height", window.innerHeight);
$container.css("height", bodyHeight);
div {
display: block;
width: 100%;
margin: 0;
}
#body {
overflow-y: scroll;
}
#container {
overflow-y: hidden;
}
#header {
overflow: hidden;
}
#navbar {
height: 10px;
background-color: brown;
}
#mainContent {
height: 200px;
overflow-y: scroll;
}
#contentP {
height: 400px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="body">
<div id="container">
<div id="header">
<h1>Header</h1>
</div>
<div id="navbar">
</div>
<div id="mainContent">
<p id="contentP">This is content</p>
</div>
</div>
</div>
Why is there overflow if the div is sized to fit in the window?
EDIT: So far, answers haven't helped. This is the site I'm working on. It's joomla. I want the nav bar to lock at the top of the screen.
$(document).ready(function() {
//Declare some variables
var $window = $(window),
$body = $(".body"),
$mainContent = $("#maincontent"),
headerGap = parseFloat($("#headerimg").css("margin-top")),
headerHeight = headerGap + $("#header").height() + parseFloat($("#navbar").css("margin-top")),
navbarHeight = $("#navbar").height(),
footerHeight = $("#footer").height();
//set the height of the body and the maincontent
resizePage();
//Set the listeners for resizing and scrolling
$window.resize(resizePage);
$window.scroll(scrollHandler);
//When you scroll, see if the navbar is at the top. Set maincontent overflow
//to scroll when the navbar is at the top of the window. Set it to hidden otherwise
function scrollHandler() {
if ($window.scrollTop() < headerHeight - 1) {
$mainContent.css("overflow", "hidden");
} else {
$mainContent.css("overflow", "auto");
}
}
//Set the body and the mainContent to be the correct sizes when the window size is changed. In theory, the body should be:
// windowHeight + headerHeight
// maincontent should be:
// windowHeight - (headerHeight + navbarHeight + footerHeight)
// But that doesn't quite work out.
function resizePage() {
//Deal with the changing CSS due to media queries
if ($(window).width() > 768) {
headerGap = parseFloat($("#headerimg").css("margin-top"));
headerHeight = headerGap + $("#header").height() + parseFloat($("#navbar").css("margin-top")) - 1;
$(".nav.menu.nav-pills").css("width", "92.5%");
}
else {
headerHeight = $("#header").height();
$(".nav.menu.nav-pills").css("width", $window.width());
}
//The header and navbar height change at certain sizes, so grab them again to be safe.
navbarHeight = $("#navbar").height();
footerHeight = $("#footer").height();
var windowHeight = $window.height(),
contentHeight = windowHeight - (footerHeight + navbarHeight);
//if we account for headerHeight too, maincontent is too big
resizeContent(contentHeight);
resizeBody(windowHeight);
}
//The body should take up the whole height of the window, plus the header
//and margin heights at the top. This way, you scroll to the navbar.
// But it doesn't work this way.
// -7 and -27 are from eyeballing it.
function resizeBody(windowHeight) {
if($window.width() > 728) {
$body.css("height", windowHeight - 7);
}
else {
$body.css("height", windowHeight - 27);
}
}
// The content should go from the bottom of the navbar to the bottom of the footer.
//
function resizeContent(contentHeight) {
$mainContent.css("top", (headerHeight + navbarHeight));
$mainContent.css("bottom", (0 - headerHeight));
//For the background slideshow on the Furniture page
// Again, + 5 was eyeballed
$("div.moduletable").css("height", contentHeight + 5);
if ( (contentHeight + 5) < ($(window).width()) /2 ) {
$(".wk-slideshow img").css("width", "100%");
$(".wk-slideshow img").css("height", "auto");
}
else {
$(".wk-slideshow img").css("height", contentHeight + 5);
$(".wk-slideshow img").css("width", "auto");
}
}
});
It works for a lot of sizes, but one you get to small resolutions it falls apart.
EDIT 2: I was able to get the effect I was going for by adding another div. I set the body to be the height of the window and the new div to be the size of the body + the height of the header. The body has "overflow-y: scroll". The container would have "overflow-y: hidden" (See updated snippet). This doesn't totally answer my question, but at least it helps?
I've taken a look at your code and altered it. Try this and see if this is what you're looking for.
In my example i'm looking for the element by getElementById and then I set it's style.height to window.innerHeight - 10px without taking the 10px it wouldn't show the border fully on the page. So you just remove 10px's. The example has been tested on different screen sizes.
Javascript example:
function autoResizeDiv() {
document.getElementById('body').style.height = window.innerHeight - 10 + 'px';
console.log(window.innerHeight - 10 + 'px');
}
window.onresize = autoResizeDiv;
autoResizeDiv();
#body {
display: block;
border: 5px solid black;
}
body {
overflow: hidden;
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="body">
</div>
The following worked for me:
$(".body").height($(window).height());
I figured out the biggest problem. I was using some absolutely positioned elements without giving a parent any other position. This made things show up wonky when I was trying to size other things. I also needed to have an extra div as a container for all the content on the page that would be the height of the window + the height of the header.
Thanks to everyone who answered, it helped!

How to zoom in an image and center it?

Any Idea how to zoom in a image on particular point using javascript, css ? I am using webkit based browser.
I can zoom by specifying zoom property , like `elem.style.zoom="150%",
Main problem is I cannot center the image where I want to zoom.
I can get the point where I want to zoom using mouseclick.
As I said in my comment above, I would avoid the zoom css property and stick to just javascript. I managed to throw together the following code which works pretty well for the first click, really all it needs is a little more dynamically (even a word?).
<html>
<head>
<script type="text/javascript">
function resizeImg (img)
{
var resize = 150; // resize amount in percentage
var origH = 200; // original image height
var origW = 200; // original image width
var mouseX = event.x;
var mouseY = event.y;
var newH = origH * (resize / 100) + "px";
var newW = origW * (resize / 100) + "px";
// Set the new width and height
img.style.height = newH;
img.style.width = newW;
var c = img.parentNode;
// Work out the new center
c.scrollLeft = (mouseX * (resize / 100)) - (newW / 2) / 2;
c.scrollTop = (mouseY * (resize / 100)) - (newH / 2) / 2;
}
</script>
<style type="text/css">
#Container {
position:relative;
width:200px;
height:200px;
overflow:hidden;
}
</style>
</head>
<body>
<div id="Container">
<img alt="Click to zoom" onclick="resizeImg(this)"
src="https://picsum.photos/200" />
</div>
</body>
</html>
It works in Google Chrome and IE, not sure about others. Like I said hopefully it will point you in the right direction.
What has to be done.
Get the location of the click inside the image. This might seem easy but it is not because the pageX and pageY of the event hold the coordinates in regard to the document. To calculate where inside the image someone clicked you need to know the position of the image in the document. But to do this you need to factor in all the parents of it, as well as if they are relative/absolute/static positioned .. it gets messy..
calculate the new center (the click position scaled - the top/left position of the container)
scale the image and scroll the container to the new center
if you do not mind using jQuery for it then use the following (tested)
<script type="text/javascript">
$(document).ready(
function(){
$('#Container img').click(
function( event ){
var scale = 150/100;
var pos = $(this).offset();
var clickX = event.pageX - pos.left;
var clickY = event.pageY - pos.top;
var container = $(this).parent().get(0);
$(this).css({
width: this.width*scale,
height: this.height*scale
});
container.scrollLeft = ($(container).width() / -2 ) + clickX * scale;
container.scrollTop = ($(container).height() / -2 ) + clickY * scale;
}
);
}
);
</script>
and the html needed
<div id="Container">
<img alt="Click to zoom" src="http://sstatic.net/so/img/logo.png" />
</div>
In following code, the image is amplified at the mouse click point - the image is amplified, but the point where you clicked remains under your mouse cursor, and the size of the frame remains the same. Right-click to go back to original display ratio.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<style>
div {
width: 400px;
height: 600px;
overflow: hidden;
}
img {
position: relative
}
</style>
<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<script type="text/javascript">
var imageOffset_x = 0;
var imageOffset_y = 0;
function onZoom()
{
var mouseInFrame_x = event.x;
var mouseinFrame_y = event.y;
var mouseInImage_x = imageOffset_x + mouseInFrame_x;
var mouseInImage_y = imageOffset_y + mouseinFrame_y;
imageOffset_x += mouseInImage_x * 0.16;
imageOffset_y += mouseInImage_y * 0.16;
var image = $('#container img');
var imageWidth = image.width();
var imageHeight = image.height();
image.css({
height: imageHeight * 1.2,
width: imageWidth * 1.2,
left: -imageOffset_x,
top: -imageOffset_y
});
}
function onRightClick() {
imageOffset_x = 0;
imageOffset_y = 0;
$('#container img').css({
height: 600,
width: 400,
left: 0,
top: 0
});
return false;
}
</script>
</head>
<body>
<a id="zoom" href="#" onclick="onZoom();">Zoom</a>
<div id="container">
<img src="~/Images/Sampple.jpg" width="400" height="600" onclick="onZoom();" oncontextmenu="onRightClick(); return false;"/>
</div>
</body>
</html>

Categories