I need to know how one can get the maximum possible width of a div. Generally, a <div>'s width is limited by it's parent, meaning that it can not be larger than a certain amount. How that certain amount can be calculated?
I need this to calculate if the text inside the current <div> has overflown, (since the only way to detect a text overflow is to compare it's current width to its current clientWidth).
Thanks!
A couple ways to do this, let's start with your div...
<div id='mr_cleaver'>
<div id='beaver'>Blah</div>
</div>
...and then someJavascript:
//Method One: Find the width of the div's parent
var max_beaver_width = $('mr_cleaver').offsetWidth
//Method Two: Max out the div, find length, return to original size.
var beaver_width = $('beaver').offsetWidth;
$('beaver').style.width = "100%";
var max_beaver_width = $('beaver').offsetWidth;
$('beaver').style.width = beaver_width + 'px';
//Method Three: Check for overflow
$('beaver').scrollWidth > $('beaver').offsetWidth ? alert("Over") : alert("Within")
Thanks Steve!
Your suggestions were very helpful. Although none of them worked for me(probably I didn't explain my situation very well), but using your hints, I could find a way to detect text overflow:
/* specifying the height of 'beaver'*/
var font_size= $('beaver').css("font-size");
font_size = parseInt(font_size.replace(/[a-z]*/gi,''));
var maxHeight = font_size + 4; // 4 is to make sure that the font fits in the maxHeight
/*now calculate current height*/
$('beaver').style.overflow-y:visible;
$('beaver').style.overflow-x:hidden;
var cuurentHeight = $('beaver').clientHeigth;
/* check whether overflow is occured*/
if(cuurentHeight > maxHeight){
//overflow has been occured
}
If you want the div to be 100 % in width with no space between the edges, you can try to add this simpel CSS style to the div:
<style type="text/css">
#FullWidthDiv { // EDIT
position: absolute; // If you use 'fixed' as position, then the div
display: block; // won't become smaller when the screen is at is smallest.
float: left; // The fixed position is good when you for example want the
width: 100%; // menu to stay in place.
background-color: #06F;
height: auto;
left: 0px;
top: 0px
}
</style>
<html>
<body>
<div id="FullWidthDiv"></div>
</body>
</html>
You can append a div into parent element to measure it.
var test = document.querySelector('#test');
var div = document.createElement('div');
div.style.width = '10000px';
test.appendChild(div);
var maxWidth = test.offsetWidth;
test.removeChild(div);
alert(maxWidth);
#test {
display: inline-block;
max-width: 100px;
}
<div id="test"></div>
Related
How to get CSS height and width if they are in percentage value using JavaScript?
Lets say the CSS rule:
.field {
height:50%;
width:25%;
}
What we tried:
let a = document.getElementById("field");
console.log(a.style.height)
This give me empty string. Is there any way to get height in percentage using JavaScript?
The height of an element a as a percentage of its parent can be calculated as
getComputedStyle(a).height.replace('px','') / getComputedStyle(a.parentElement).height.replace('px','') * 100 + '%'
This works however the styles of a and its parent have been set (through classes, through inline style setting). It is not the same as finding out whether the heights were set by a percentages or by other units initially.
Here's a simple example:
let a = document.querySelector(".field");
console.log(getComputedStyle(a).height.replace('px','') / getComputedStyle(a.parentElement).height.replace('px','') * 100 + '%');
.container {
height: 50vh;
width: 30vw;
}
.field {
height:50%;
width:25%;
}
<div class="container">
<div class="field"></div>
</div>
Height = a.offsetHeight
Width = a.offsetWidth
This gives height and width in pixels. Doesn't matter how it's declared in CSS.
in css rule,field is with dot = class and in js, you are trying getElelmentById.
Change .field to #field in css rule and try ...
#field{
height:50%;
width:25%;
}
You can use getComputedStyle
let elem = document.getElementById('field');
let ht = window.getComputedStyle(elem, null).getPropertyValue("height");
console.log(ht)
I am developing a web application using AngularJS. I find myself in a situation where I have a bar (with the css I created a line) that must dynamically lengthen and shorten.
I know that JQuery scripts are sufficient to do this. For example, if my css is like this:
.my_line{
display:block;
width:2px;
background: #FFAD0D;
height: 200px; /*This is the part that needs to dynamically change*/
}
I could in the controller resize the line (of my_line class) simply with:
$(".my_line").css("height", someExpression*100 + 'px');
The thing is, I would like to dynamically resize the line based on the size of another div element (Or, in general, any HTML element of my choice).
I don't know how to get (at run-time) the size of a certain page element in terms of height.
Only in this way I would be able to create a line that dynamically lengthens or shortens as the size of a div (or some other element) changes!
How do you do this? So I will avoid writing hard-coded the measures but I want make sure that they vary as the dimensions of other elements on the page vary
I hope this is helping:
$(".my_line").css("height", $("#referenceElement").height()*5 + 'px');
.my_line{
display:inline-block;
width:2px;
background: #FFAD0D;
}
#referenceElement {
display:inline-block;
background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="my_line"></div>
<div id="referenceElement">Hi, I'm 5 time smaller than the orange line!</div>
Here I am using the setInterval to track the div's height (you can do width as well) and storing it in a previousHeight variable and comparing it every interval
Then according to the comparison, it will determine if the height of the div has changed. If it has then it will change the height of the other div according to the height of the first div
You can create multiple variables and track multiple elements in the same setInterval
$(document).ready(function(){
var previousHeight = parseInt($("#my-div").css("height"));
setInterval(function(){ checkHeight(); }, 100);
function checkHeight() {
// Check height of elements here
var currentHeight = parseInt($("#my-div").css("height"));
if(currentHeight != previousHeight) {
previousHeight = currentHeight;
$("#dynamic-div").css("height", parseInt(currentHeight) + "px");
}
}
$("#button").click(function() {
$("#my-div").css("height", parseInt(previousHeight) + 5 + "px");
})
})
#my-div{
background: #000000;
height: 20px;
width: 20px;
}
#dynamic-div{
background: teal;
height: 20px;
width: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="my-div">
</div>
<button id="button">Increase div height</button>
<div id="dynamic-div">
</div>
I've made a timeline using a sort of following this: https://www.w3schools.com/howto/howto_css_timeline.asp and set it to position: sticky. This is in a container called, div.timeContainer. Next to it, there's some text in a separate div. The idea is that the user scrolls down, reading the text on the right, while the timeline/overview on the left is in view.
The problem right now is that if I set the height of div.timeContainer, resizing the window means that the timeline will stop being in view/sticky around half-way through since the div on the right has become longer.
This (and variations) is what I have tried so far:
const historyContainer = document.querySelector("div.history").style.height
document.querySelector("div.timeContainer").style.height = historyContainer
I have prepared for you a simple example of assigning parent height to a child. An example in vanilla js.
let parent_div = document.querySelector('.parent');
let child_div = document.querySelector('.child');
let click_button = document.querySelector('input');
click_button.onclick = function(){
child_div.style.height = parent_div.offsetHeight + 'px';
};
.parent {
width: 100%;
height: 300px;
background-color: yellow;
}
.child {
width: 50%;
background-color: green;
}
<input type="button" value="click me to get the height of the child div">
<div class="parent">
<div class="child">
</div>
</div>
I am trying to wrap text around an image that is positioned on the right and have the image shifted below the text when the screen becomes too small.
With these additional requirements:
The Text component has a minimum width for it's content next to the column (say 300px), which when exceeded pushes the image below the text.
The image component's size is unknown.
Images will be rendered at their native size, which may determine whether it is rendered to the right of the text or below it.
The same rules must apply when printing
Example
What have I tried?
https://codepen.io/CrocoDillon/pen/kmGCw (flawed as the image size is not pre-determined)
My current solution is a combination of various approaches. It's dirty/hacky as it uses JS to achieve part of it's goals which end up failing the print requirement.
It works as follows:
In html, render the IMAGE after the TEXT and floating the IMAGE to the right so that image is on right with text wrapped around it.
In JS, on window resize, if windowWidth - imageWidth > 300px (our min content width), update the style of the container to use flex-direction column-reverse so that the image appears below the text.
It fails the Print Requirement as the min-width check happens on window resize based on widths within window. Ideally it should now be based on the widths within the paper size/layout.
It is as follows:
HTML:
<div class="article-template-1">
<div class="article-content" ng-style="articleContentResponsiveStyle">
<div class="main-image-holder">
<div ng-repeat="imageLink in images">
<img ng-attr-src="{{imageLink.Location}}"
ng-attr-title="{{imageLink.Description}}" />
</div>
</div>
<span model="Article.Content" bind-html-compile>{{Article.Content}}</span>
</div>
</div>
CSS:
#newsArticle .article-content-holder .article-template-1 .article-content .main-image-holder {
float: right;
display: flex;
width: fit-content;
flex-direction: column;
}
#newsArticle .article-content-holder .article-template-1 .article-content .main-image-holder img {
max-width: 100%;
width: fit-content;
}
Controller:
var appWindow = angular.element(this.$window);
appWindow.bind("resize", this.updateArticleResponsiveStyle);
private exceedsMinContent:boolean = null;
private updateArticleResponsiveStyle = () => {
// The minimum size that inline content needs to be before images are repositioned
const minArticleWidth = 300;
let windowWidth = window.innerWidth;
let maxImageContainerWidth = windowWidth - minArticleWidth;
let imageContainerWidth = angular.element(document.getElementsByClassName('main-image-holder'))[0].getBoundingClientRect().width;
const previouslyExceedsMinContent = this.exceedsMinContent;
this.exceedsMinContent = imageContainerWidth > maxImageContainerWidth;
if (previouslyExceedsMinContent !== this.exceedsMinContent) {
this.$scope.articleContentResponsiveStyle =
this.exceedsMinContent ?
{
"display": "flex",
"flex-direction": "column-reverse"
} :
{
"display": "block"
}
this.$scope.$apply();
}
}
Yes, I find this incomplete solution hacky and would prefer a pure CSS approach if possible.
What i'm trying to do is make the title of a blog post exactly half the width of the blog description and align itself at 50% of the width of the blog description.
This is what i tried in JS:
var post_title_width = document.getElementById("post_desciption").offsetWidth;
var post_title_width = post_description * 0.5;
document.getElementbyId("post_title").style.width = post_title_width;
HTML:
<div class="post">
<span class="post_title">This is a test title, testing some javascript...........</span><br>
<span class="post_description">Hello this is a test description right here, just to test some code im trying to do</span>
</div>
I am not using css because i want to test javascript and learn how to use it efficiently.
If you really want to do it in javascript, you've got a few problems:
You're trying to target class names with getElementbyId
Your variable names are messed up
Spans are not block elements, so setting the width isn't applicable unless you set overflow and change the display to block or inline-block
http://jsfiddle.net/cmweU/
var post_description = document.getElementsByClassName("post_description")[0],
post_description_width = post_description.offsetWidth,
post_title_width = ( post_description_width * 0.5 ) + "px";
document.getElementsByClassName("post_title")[0].style.width = post_title_width;
Try this (example):
HTML
<div id="head"><div id="half"></div></div>
CSS
#head {
width: 300px;
height: 100px;
background: purple;
}
#half {
height: 100%;
background: green;
}
JS
document.getElementById("half").style.width = document.getElementById("head").offsetWidth / 2 + 'px';
JS for margin inner block at the center of it's countainer try to use this (example):
document.getElementById("half").style.marginLeft = (document.getElementById("head").offsetWidth - document.getElementById("half").offsetWidth) / 2 + 'px';