How to fit content of a DIV with fixed height - javascript

Consider that we have a DIV with fixed height. Without a defined width, the content will spread to the width of 100%. How to adjust the width to fill the DIV. Definitely, it is not posible with CSS, thus, I am looking for a solution with Javascript.
In this example, the text is spread across the width of 100% and leaves lots fo empty space in the fixed height. I need to set a width of 130px by javascript to fit the content to the entire DIV. But how to calculate the width?
NOTE: This value (130px) was estimated for the example text. Depending on the DIV content, javascript needs to calculate the width required to fit the content within the DIV.
Is there any way to estimate the 2D size of a DIV content?
CSS actually does this for height; when we have a fixed width, it continues the height to fill the DIV. Is it possible to do so for width too?
Clarification: How to vertically fill the DIV without knowing the width (we have a fixed height)?

If I understand your requirement correctly, you can do this using Javascript.
The trick is to use a helper <div> within which you let the browser flow the content to a specific width and see what height it comes up with. If the height of the helper <div> is more than that of the outer <div>, adjust the width to compensate.
Meanwhile, the outer <div> has overflow: hidden so all those flowing experiments don't produce jarring changes to your page layout.
See it in action.

This is an alternate approach.. While less efficient, it may be more accurate than my other answer.
see example here:
Basically loop the width down until the desired height is reached
<div id="AA">
<div id='A'>
I dont know how wide i am, I dont know how wide i am, I dont know how wide i am, I dont know how wide i am, I dont know how wide i need to be
</div>
</div>
The CSS:
#AA {
height: 300px;
border: 1px solid black;
width: 100%;
}
#A {
display: inline;
}
The Script:
height = $('#AA').height();
minWidth = 300;
currentWidth = $('#A').width();
currentHeight = $('#A').height();
stop = false;
if (currentWidth >= minWidth) {
while (stop === false) {
if (currentWidth >= minWidth) {
newWidth = currentWidth - 1;
$('#AA').width(newWidth);
currentHeight = $('#A').height();
currentWidth = $('#A').width();
if (currentHeight < height) {
stop = false;
}
else {
stop = true;
}
}
else {
stop = true;
}
}
}

Related

Add sidebar to the right of webpage that resizes and shifts everything accordingly

I'm creating an Chrome Extension, which should add sidebar to all webpages.
This sidebar shouldn't overlap webpage content, it should be placed next to the existing content, essentially shrinking width of body of webpage to initial width - sidebar width.
This is the code I came up with, but I have a problem with some pages like stackoverflow for instance, see how top bar doesn't shrink like the rest of the page does (screenshots attached below the code)
// create sidebar
const sidebar = document.createElement("iframe");
sidebar.src = chrome.extension.getURL("iframe/iframe.html");
sidebar.id = "extensionSidebar";
sidebar.frameBorder = "0";
sidebar.style.height = "100%";
sidebar.style.width = "100px";
sidebar.style.position = "fixed";
sidebar.style.top = "0";
sidebar.style.right = "0";
sidebar.style.zIndex = "2147483646";
// append sidebar to body
document.documentElement.appendChild(sidebar);
// shrink body
document.body.style.width = window.innerWidth - 100 + "px";
Screenshots:
https://prnt.sc/o215x5
https://prnt.sc/o21637
The top bar doesn't shrink as you would like it to do because it is fixed, it will always take 100% of the viewport width. Its CSS properties on your example with stackoverflow are :
...
position: fixed;
top: 0;
left: 0;
width: 100%; /*though it's not "really" 100vw*/
...
Even by changing the html element in CSS, in order to change its maximum size to 80% of the viewport width for instance, the navbar would still take all the viewport's width.
To understand it you can try the following fiddle, it might speak for istelf : https://jsfiddle.net/bcg2vkjm/4/
On it you can "un-comment" the body element inside the CSS and see the result, it might give you some help ! Though it only applies a scale of 1 (so it should not change...), for some reason it makes the fixed element adapt to the body size, which is what you want, you just might have to play along with the translateX and/or scale in the CSS, but it might be a risky solution because it changes quite a lot the way everything is displayed, not only the fixed element, as you can see.
In your javascript you can try the following :
document.querySelector('body').style.transform = "scaleX(something)";
for instance !

Calculating a responsive header's height and using the result in the style of another div's height

Please bear with me as I attempt to explain the issue I'm having. It's kinda tricky!
I have a fixed header that includes a responsive image, because of this, the height of the header depends on the width of the device. I also have a fixed footer sitting on the bottom of the screen. In-between the header and footer I have a fixed div with scrollable overflow positioned towards the left side of the screen. I need the fixed div in-between the header and footer to have a HEIGHT that is the following:
calc(100% - the header's height in px - the footer's height in px)
To do this, I know I need to use Javascript or jQuery, but I'm unsure how to go about setting that up. Furthermore, I need that styling to only be applied on a specific media query.
I have similar code that adds padding to the top and bottom of another div that is centered between the header and footer. This is the code that I'm using and it works perfectly (in the fiddle I've provided at the bottom, I don't use "DOMContentLoaded" because it doesn't quite work with JSFiddle like it should. same idea slightly different syntax in the fiddle) :
document.addEventListener("DOMContentLoaded", function() {
var headerHeight = document.getElementById('header').clientHeight;
document.getElementById("content").style.paddingTop = headerHeight + "px";
var footerHeight = document.getElementById('footer').clientHeight;
document.getElementById("content").style.paddingBottom = footerHeight + "px";
}, true);
window.addEventListener('resize', function() {
var headerHeight = document.getElementById('header').clientHeight;
document.getElementById("content").style.paddingTop = headerHeight+ "px";
var footerHeight = document.getElementById('footer').clientHeight;
document.getElementById("content").style.paddingBottom = footerHeight + "px";
}, true);
I need to use code similar to that, but instead of styling the div "content", I need to be styling a div titled "description" and instead of styling the padding, I need to be styling the height. The last difference is that the styling should only be applied to this media query:
#media screen and (orientation: landscape)
I've created a JSFiddle: http://jsfiddle.net/yg7mjhvn/
Thank you guys so much! I really appreciate it.
If I get it correctly, you just need to set the height of content/description div calc(100% - <header-height> - <footer-height>) with javascript.
So, to do that add a function setDescriptionHeight to your js code which sets the height of description div and add it as a load and resize event handler. All this will be done like this.
function setContentHeight() {
if (window.innerWidth > window.innerHeight) { // window.orientation === 90 for checking the real orientation
var headerHeight = document.getElementById('header').clientHeight;
var footerHeight = document.getElementById('footer').clientHeight;
document.getElementById("description").style.height = `calc(100% - ${headerHeight}px - ${footerHeight}px)`;
} else{
document.getElementById("description").style.height = "";
}
document.getElementById("description").style.top = `${headerHeight}px`;
}
window.addEventListener('load', setContentHeight, true);
window.addEventListener('resize', setContentHeight, true);
Now, you see that it has a condition window.orientation === 90. That is there to check whether the device is in landscape orientation, and if it is then the styling is done.
note that window.innerHeight < window.innerWidth simply detects whether the width is greater than the height. And, window.orientation === 90 checks the device orientation and it won't be 90 for a laptop or a dekstop screen. Moreover, it is deprecated now and you can see more about it here

Auto-resize elements based on container size without using scale

Example:
Just having a problem with the computation to auto adjust width of element-image and font size of the element-text based on the container's width. It's like,
$('.element-image').width() = $('.container').width() - $('.element-image').width();
$('.element-text').css('font-size') = $('.container').width() - $('.element-text').css('font-size');
<div class="container">
<img class="element-image" src="sample.jpg" />
<span class="element-text">Sample Text</span>
</div>
something like that but I can't get the logic. Can someone help? Note that this is for my web app, it's like an ad or graphic builder.
Here's the sample app:
https://drive.google.com/file/d/1dnsRg6TjLqUx6IzgLwOYq5uNJrrx7dUv/view?usp=drivesdk
Scaling images is trivial, just use percentage widths.
Scaling text is harder. You can use viewport units to scale the text based on the window size:
.element-text {
font-size: 10vw
}
<span class="element-text">Sample Text</span>
<div>Unscaled text (put this snippet in "fullscreen" mode and change the window size to see the effect)</div>
...but if you need text to scale to exact container sizes, you'll need to resort to javascript. The following is a (kind of dumb) method for setting the font-size to match the container size -- you wouldn't use short-interval polling in real life, and would probably do something smarter than simply incrementing / decrementing the font-size at each step, but this should suffice for demonstrating the technique:
window.setInterval(function() { // In real life you'd likely use the window resize event
var ewidth = $('.element-text').width();
var cwidth = $('.container').width();
var fontsize = parseInt($('.element-text').css("font-size"));
// change font size if the text block doesn't match the container width
if (ewidth > cwidth - 20) { // leave a little extra space to prevent jitter
$('.element-text').css("font-size", --fontsize);
} else if (ewidth < cwidth ) {
$('.element-text').css("font-size", ++fontsize);
}
}, 1);
.container {
resize: both;
overflow: hidden;
border: 1px solid;
width: 20px;
}
.element-image {
width: 100%
}
.element-text {
white-space: nowrap
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Resize me:
<div class="container">
<span class="element-text">Sample Text</span>
<img class="element-image" src="http://placehold.it/200x200" />
</div>
This jQuery plugin uses much the same technique. In its source code is the following comment block:
// I understand this is not optimized and we should
// consider implementing something akin to
// Daniel Hoffmann's answer here:
//
// http://stackoverflow.com/a/17433451/1094964
//
...which is maybe the most roundabout way I've ever discovered a potential question duplicate. (Clearly I need to pay more attention to the "related questions" list, because there it is right at the top of it...)
You dont have to do it with jquery. You can use CSS width:100%; or any percentage for that and it will generate a width accorind to its parent width.
Check this DEMO to understand.
I didnt really got what do you need but im fixing your jquery
var contwidth = $('.container').width();
var imgwidth = $('.element-image').width();
$('.element-image').width(contwidth - imgwidth);
$('.element-text').css('font-size',contwidth - imgwidth);
<div class="container">
<img class="element-image" src="sample.jpg" />
<span class="element-text">Sample Text</span>
</div>
btw as you are changing the width of the image, what is the logic of calculating container width - image width? This will be an error because as you trying to get the width of image the other function changes it. never ending cycle.

JS scrollbar with fluid height

I'd like to personalize the scrollbar of a div whith a fluid height :
section {
max-height:70%;
overflow-y:auto;
}
I have found two smart light snippets : a Jquery plugin (http://baijs.nl/tinyscrollbar/) and a pure JS one (http://gondo.webdesigners.sk/javascript-scrollbar/). The problem is that these snippets do not accept % value for the height. For example, with tinyscrollbar, i have to put this :
section .viewport {
width: auto;
height:440px;
overflow: hidden;
position: relative;
}
If I put "height:100%;" or "height:auto;", the content disappears ! Why does it accept px and not % ? I'd like to understand it...
Which part of the JS/JQuery code should I change/add in order to insert the fluid height of the section ?
It's hard to follow without more example code (get in the habit of posting more code please), but I think something like this is what you're after.
--- Why don't you track the height of the context (outer div?) and the height of the inner div (section) and calculate them as they change?
var context_height = $("#context_div").height();
var section_height = $("section#id").height();
var percentage = section_height / context_height;
var measurement = percentage + "%";
$(section_height).css("height", measurement); // trigger this with a callback if heights need updating - possibly even re-initializing any scroll plugins, if necessary.

Get the width of the viewport and apply it to a tag or class width

I have horizontal layout and it has 5 inline divs. Is there a way in javascript to get the width of the users' viewport then apply it to the each content panel tags width, so it will be 100% in every content panel? I need it to be 100% of the viewport because there are parallax elements inside it
I have tried this css code below but the panels are just stacking on top of each other.
#contentPanel { width: 100%; float: left;}
I really don't know if the questions makes any sense, because I've been up for 16 hours searching and trying to work this out.
It's easy with JQuery:
var fullDiv = $("div");
var viewportWidth = $(window).width();
var viewportHeight = $(window).height();
$("body, html").width(3*viewportWidth);
fullDiv.width(viewportWidth);
fullDiv.height(viewportHeight);
Simple Demo.
You will want to update the divs when the browser is resized probably, currently it only works when it first loads. Read more about .resize().

Categories

Resources