Dynamically assign height to a div - javascript

I want to do this: <div class="container" style="height: calc(100vh - 349px);"> but dynamically through JavaScript because the "394" will vary.
I did this:
<script>
var afooter = document.getElementById('footer').positionInfo.height;
var acontainer = document.getElementById('container').positionInfo.height;
var dif = parseInt(acontainer) - parseInt(afooter);
document.getElementById('contenedor').setAttribute('style','height: calc(100vh -' + dif + '');
</script>
What I am doing wrong?

Try this function.
function resizeElementHeight(element) {
var height = 0;
var body = window.document.body;
if (window.innerHeight) {
height = window.innerHeight;
} else if (body.parentElement.clientHeight) {
height = body.parentElement.clientHeight;
} else if (body && body.clientHeight) {
height = body.clientHeight;
}
element.style.height = ((height - element.offsetTop) + "px");
}

I found a workaround disabeling some things instead of not showing them, so the footer now has a fixed height. That way the <div class="container" style="height: calc(100vh - 349px);">is now working.
Thank you very much all for your help.

Related

Addclass when div width is greater than 80%

How to addclass when div width is greater than 80% ?
This is what I just tried
<div class="wrap_bar">
<div class="bar" style="width:50%;"></div>
</div>
<div class="box"></div>
<script>
var barTotal = $(".bar");
var box= $(".box");
var width = barTotal.width();
if (width > 80%)
box.addClass('type2')
</script>
This code is not working well. Please help
If you need this dimension detection only one time (when DOM loaded) then you can just following approach.
function addWhenResized(element){
var parentWidth = $(element).parent().width();
var elementWIdth = $(element).width();
if( (elementWIdth / parentWidth)*100 > 79){
$('.box').addClass('type2');
}
else {
$('.box').removeClass('type2');
}
}
$(document).ready(function(){
addWhenResized('.bar');
})
But main challenge will be there if you want detect the run time dimension change. Then need to take help from here: http://marcj.github.io/css-element-queries/
After added the plugins from above given link you should follow the following approach:
function addWhenResized(element){
var parentWidth = $(element).parent().width();
var elementWIdth = $(element).width();
if( (elementWIdth / parentWidth)*100 > 79){
$('.box').addClass('type2');
}
else {
$('.box').removeClass('type2');
}
}
new ResizeSensor(jQuery('.bar'), function(){
addWhenResized('.bar');
});
Try this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var barTotal = $(".bar");
var barTotalWidth = barTotal.width();
var box= $(".box");
var boxWidth = box.width();
var widthPercent = boxWidth / barTotalWidth;
console.log(widthPercent);
if (widthPercent > 0.8)
box.addClass('type2');
});
</script>
<div class="bar" style="width:200px;height:100px;background-color:red"> </div>
<div class="box" style="width:190px;height:80px;background-color:blue"> </div>
your codes don't work because you've just called javascript once when the page loaded , you have to wrap it into an event !
Take a look
that answer
or that answer
jQuery(document).ready(function($) {
if ($(this).width() > 768) {
$('#service-1').addClass('row text-center');
} else {
$('#service-1').removeClass('row text-center');
}
});
this will work fantastic when width is less than or more than will add or remove the class

Change div's width by a value in JS

How to change div's width by a certain value, like this:
someDiv.style.width += "100px";
It works when I want to set a value (i.e. width = "100px") but the problem is with += operator.
This would work for a vanilla javascript solution (since you didn't mention jquery):
var someDiv = document.getElementById("someDiv");
var w = 0;
if (typeof someDiv.clip !== "undefined") {
w = someDiv.clip.width;
} else {
if (someDiv.style.pixelWidth) {
w = someDiv.style.pixelWidth;
} else {
w = someDiv.offsetWidth;
}
}
someDiv.style.width = (w + 100) + "px";
<div id="test" style="height:100px"></div>
var elem=document.getElementById("test");
height=parseInt(elem.style.height);
height+=100;
height+="px"
console.log(height);
Try the following
http://jsfiddle.net/CME3Y/
That is because Javascript can't understand what "100px" + "100px" means, since those are string values.
I would do it like this using jQuery:
$(someDiv).width($(someDiv).width() + 100);
var currentwidth= $('#div').width();
$('#div').width(currentwidth +100);
http://jsfiddle.net/dolours/CME3Y/1/
Also you can use this https://stackoverflow.com/a/6179629/1479798

javascript check document for element to apply a value

i'm pretty new to javascript and have been stuck on this all day. I have a script which resize element according to screen res it all works except I need to have "if element DOES NOT exist on document then add an addittional value "242px" into contentContainer.css method" this is what I have so far so that this eleemnt takes up the space of the asideContent element when its not on the page...
<script>
// DOM Container Resize Handler
var extra = ($("body.asideContent").length == 0) ? 242 : 0;
var adjustStyle = function() {
var winWidth = $(window).width(),
width = parseInt(winWidth),
container = $('body .fixed');
contentContainer = $('body .content');
if (width >= 1454) {
container.css('width','1454px');
contentContainer.css('width',extra + 1210 + "px");
} else if ((width < 1454) & (width >= 1212)) {
container.css('width','1212px');
contentContainer.css('width',extra + 968 + "px");
} else {
container.css('width','970px');
contentContainer.css('width',extra + 726 + "px");
}
};
$(function() {
var filterWrap = $("#filterWrap"),
offset = filterWrap.offset(),
topPadding = 15;
$(window).scroll(function() {
if ($(window).scrollTop() > offset.top) {
filterWrap.stop().animate({
marginTop: $(window).scrollTop() - offset.top + topPadding
});
} else {
filterWrap.stop().animate({
marginTop: 0
});
};
});
// DOM Container Resize Handler - Initialization
$(window).resize(function() {
adjustStyle();
});
adjustStyle();
});
</script>
Its applying the extra all the time, add I only want to apply this when ("body.asideContent") is not in the document
test html
<html>
<head>
</head>
<body>
<div class="fixed">
<div id="container">
<div class="asideContent">&nbsp</div>
<div class="content">&nbsp</div>
</div>
</div>
</body>
</html>
Just want to say thank you in advance for any help you can give me... its been driving me crazy all day...
body.asideContent means a body with a class of asideContent. Try
$("body .asideContent")
(aka, with a space between body and .asideContent)

Re-sizing site's Body and iframe when the page link is clicked

I have an iframe that loads a page inside it.. when a link is clicked on the page in the iframe, resize the body of the parent aka the document that has the iframe's body..
Body <------------------------
Iframe |
Page |
Link... Upon Click, resize body --
How do I do the above? I tried Parent.document.body.style.width = "200px". and it didn't work. Not sure what to do. Please Help!
function Parentresize(id)
{
var newheight = 2000;
var newwidth = 2000;
parent.document.getElementById(id).height= (newheight) + "px";
parent.document.getElementById(id).width= (newwidth) + "px";
}
I think you have missed the style.height and style.width
This is the code I used in iframe
<script language="javascript">
function Parentresize(id)
{
alert("U r there");
var newheight = 200;
var newwidth = 200;
parent.document.getElementById(id).style.height = newheight + "px";
parent.document.getElementById(id).style.width = newwidth + "px";
}
</script>
<a href="javascript:Parentresize('sam');" >Call Me </a>
Ok I figured it out. This code will exactly do that. It is a bit lengthy because of extra code for cross browser compatibility:
function WindowSize()
{
WinWidth = 0, WinHeight = 0; //Initialize variables with a value of 0;
if(typeof(parent.window.innerWidth) == 'number') //Well I need the parent width of the iFrame aka browser width. Width is a number, not undefined..
{
//FireFox/Opera..
WinWidth = parent.window.innerWidth;
WinHeight = parent.window.innerHeight;
}
else if(parent.document.documentElement && (parent.document.documentElement.clientWidth || parent.document.documentElement.clientHeight))
{
//IE 6+
WinWidth = parent.document.documentElement.clientWidth;
WinHeight = parent.document.documentElement.clientHeight;
}
return WinWidth;
}
function BodyResize(ID)
{
var IDTag = parent.document.getElementById(ID);
if(IDTag.clientWidth == '1024')
IDTag.style.width = (WindowSize() + 'px');
else
IDTag.style.width = '1024px';
}
just call this function BodyResize(ID)
as
<body id="mainbody" onClick="BodyResize('mainbody')"> or <iframe id="interframe" onClick="BodyResize('interframe')">

Font size auto adjust to fit

I'm trying to do what the title says. I've seen that font-size can be a percentage. So my guess was that font-size: 100%; would do it, but no.
Here is an example: http://jsfiddle.net/xVB3t/
Can I get some help please?
(If is necesary to do it programatically with js there is no problem)
This question might help you out but I warn you though this solves it through jQuery:
Auto-size dynamic text to fill fixed size container
Good luck.
The OP of that question made a plugin, here is the link to it (& download)
BTW I'm suggesting jQuery because as Gaby pointed out this can't be done though CSS only and you said you were willing to use js...
Can't be done with CSS.
100% is in relation to the computed font-size of the parent element.
reference: http://www.w3.org/TR/CSS2/fonts.html#font-size-props
For a jQuery solution look at Auto-size dynamic text to fill fixed size container
I was looking into this for work and I liked tnt-rox's answer, but I couldn't help but notice that it had some extra overhead that could be cut out.
document.body.setScaledFont = function(){
this.style.fontSize = (this.offsetWidth*0.35)+'%';
return this;
}
document.body.setScaledFont();
Cutting out the overhead makes it run a little bit quicker if you add it to an onresize event.
If you are only looking to have the font inside a specific element set to resize to fit, you could also do something like the following
window.onload = function(){
var scaledFont = function(el){
if(el.style !== undefined){
el.style.fontSize = (el.offsetWidth*0.35)+'%';
}
return el;
}
navs = document.querySelectorAll('.container>nav'),
i;
window.onresize = function(){
for(i in navs){
scaledFont(navs[i]);
}
};
window.onresize();
};
I just noticed nicolaas' answer also had some extra overhead. I've cleaned it up a bit. From a performance perspective, I'm not really a fan of using a while loop and slowly moving down the size until you find one that fits.
function setPageHeaderFontSize(selector) {
var $ = jQuery;
$(selector).each(function(i, el) {
var text = $(el).text();
if(text.length) {
var span = $("<span>").css({
visibility: 'hidden',
width: '100%',
position: 'absolute',
'line-height': '300px',
top: 0,
left: 0,
overflow: 'visible',
display: 'table-cell'
}).text(text),
height = 301,
fontSize = 200;
$(el).append(span);
while(height > 300 && fontSize > 10) {
height = span.css("font-size", fontSize).height();
fontSize--;
}
span.remove();
$(el).css("font-size", fontSize+"px");
}
});
}
setPageHeaderFontSize("#MyDiv");
And here is an example of my earlier code using jquery.
$(function(){
var scaledFont = function(el){
if(el.style !== undefined){
el.style.fontSize = (el.offsetWidth*0.35)+'%';
}
return el;
};
$(window).resize(function(){
$('.container>nav').each(scaledFont);
}).resize();
});
A bit late but this is how I approach this problem:
document.body.setScaledFont = function() {
var f = 0.35, s = this.offsetWidth, fs = s * f;
this.style.fontSize = fs + '%';
return this
}
document.body.setScaledFont();
The base document font is now set.
For the rest of your elements in the dom set font sizes as % or em and they will scale proportionately.
here I have a mootools solution:
Element.implement("fitText", function() {
var e = this.getParent();
var maxWidth = e.getSize().x;
var maxHeight = e.getSize().y;
console.log(maxWidth);
var sizeX = this.getSize().x;
var sizeY = this.getSize().y;
if (sizeY <= maxHeight && sizeX <= maxWidth)
return;
var fontSize = this.getStyle("font-size").toInt();
while( (sizeX > maxWidth || sizeY > maxHeight) && fontSize > 4 ) {
fontSize -= .5;
this.setStyle("font-size", fontSize + "px");
sizeX = this.getSize().x;
sizeY = this.getSize().y;
}
return this;
});
$$("span").fitText();
Here is another jQuery solution ...
/**
* Resizes page header font-size for the text to fit.
* basically we add a hidden span into the header,
* put the text into it and then keep reducing the super large font-size
* for as long as the height of the span exceeds the super
* tall line-height set for the test (indicating there is more than one line needed
* to show the text).
*/
function setPageHeaderFontSize(selectorString) {
jQuery(selectorString).each(
function(i, el) {
var text = jQuery(el).text();
var length = text.length;
if(length) {
var id = "TestToSeeLengthOfElement_" + i;
jQuery(el).append("<span style='visibility: hidden; width: 100%; position: absolute; line-height: 300px; top: 0; left: 0; overflow: visible; display: table-cell;' id='"+id+"'>"+text+"</span>");
var innerEl = jQuery("#"+id);
var height = 301;
var fontSize = 200;
while(height > 300 && fontSize > 10) {
height = jQuery(innerEl).css("font-size", fontSize).height();
fontSize--;
}
jQuery(innerEl).remove();
jQuery(el).css("font-size", fontSize+"px");
}
}
);
}
//you can run it like this... using any jQuery enabled selector string (e.g. h1.pageHeaders works fine).
setPageHeaderFontSize("#MyDiv");
Here's a way to find the height of the text that you are using.
It's simple and only uses javascript. You can use this to adjust your text relative to the height you want.
function getTextHeight(text, fontSize) {
var numberOfLines = 0;
var STL = text;
for(var i = 0; i < STL.length; i++){
if(STL[i] === '<'){
try{
if(STL[i + 1] === 'b' && STL[i + 2] === 'r' && STL[i + 3] === '>'){
numberOfLines++;
}
}
catch(err){
break;
}
}
return (numberOfLines + 1) * fontSize;
}

Categories

Resources