Automatic CSS Height of Div - javascript

quick question. I would like to add a JS program to control the height of one of my bootstrap divs (it's a decorative border on both sides of the page - see picture)
I don't want to have to set the height manually (i.e 2000px;)
I was trying something like this, but I couldn't manage it
css("max-height", $(window).height());
except this just fills up the screen, anyway of filling the body?
Here is the site - davidcodes.co.uk/vintarnBurmese/index.html –
David

If you are targeting modern browsers, or using modernizr, then using 'vh' units generally works better than %. When trying to size something relative to the screen height, then percentage units require that the heights of the tree going from your element up through its parents to the body all have predetermined heights. But the 'vh' units exactly capture what you want.
.yourdiv { height:100vh; }

Replace window with 'body':
$el.css('height', $('body').height());

This worked in the end (though Safari doesn't like it, FF and Chrome find it ok)
<script>
var mainSectionHeight = $(".mainSection").height();
$(".sideBar").height(mainSectionHeight + 100 + "px");
</script>

Related

CSS scale and translate issues. How do they do it properly?

This is all mobile browser related, not desktop.
I'm trying to make a certain div to maintain its dimensions relative to device screen.
So when the user zoom in/out, the DIV and its content (image) will stay the same, nor blurry, not pixelated.
It's very hard to do it XBrowser. I thought that I was almost there but then I saw it on iPhone 5S and every time I used my method, it came out blurry.
I wish it could look like they did it on this website. Please try it on mobile and wait for the footer splash to appear.
They made it so well, no matter which device you have, the splash in the footer remains the same.
Could you please help me on establishing a similar splash behavior?
I am this close to give up :(
Here's what I tried so far. A bit of code and pseudo code:
I get the current viewport width and height
I get the scaleW and scaleH by dividing the vpWidth and vpHeight by screen.availWidht and screen.acailheight accordingly.
I have a problem on choosing which scale to put in the CSS so if it's portrait, i use the scaleW or else, scaleH (Is this a good method?).
I calculate the left and top of the element in this way:
left = (vpWidth-width*scale)/2; top = (vpHeight-height*scale)/2; where width and height are the div's width and height
I calculate the 'translate' like this: translate = -((1 - scale) / 2) * 100; I saw it in the website that I talked about and frankly, it makes sense.
I then apply this code to the div style: -webkit-transform:translate(<%= translate + '%' + ',' + translate + '%' %>) scale(<%= scale %>) translateZ(0px); and of course add the left and top properties.
I'm pretty novice in CSS :( so i learn from code and examples. Not novice in coding at all.

Dealing with scroll bars and jquery .width() method

jQuery's .width() method doesn't seem to account for scroll bars. This is problematic for me, since I'd like to set the width of some children to equal the width of their parent. I used jQuery similar to the following:
$('#contentDiv').width($('#containerDiv').width())
In this example, #contentDiv is the element I'd like to size, and I want to set it to have the width of #containerDiv, which is its parent element. My problem is that this cuts off the side of #contentDiv, as seen in this fiddle.
In my actual code, I have several elements that I'm sizing with jQuery, which all need to fit in the scrollable div, so just setting the css of #contentDiv to 100% is not an option. What's the best way of dealing with scroll bar widths of divs in jQuery?
The best solution I found while working around this solution is this:
http://chris-spittles.co.uk/?p=531
jQuery is all powerful and everything but sometimes a small dash of native JS is all you need to render pixel perfect pages... I hope you will find this solution helpful!
UPDATED:
None of the jQuery width-finding methods account for the scroll bar. In my original example, using .innerWidth(true) LOOKS like it works, but only because it returns and object, which causes width to fail and the inner contents size themselves to fit in the available space, because the example wasn't very good. However, it's possible to write a function to compute the available space in a div with a scroll bar in it, which can then be used to position the contents as you wish.
To write that function, I took advantage of the fact that, when a div is appended to a div with a scroll bar in it, it takes up the full available width (i.e. the inner width of the parent minus the width of the scroll bar).
The function looks like this:
function noScrollWidth(div){
var measureDiv = $('<div id="measureDiv">');
div.append(measureDiv);
var width = measureDiv.outerWidth();
measureDiv.remove();
return width
};
I then use this to size my content div:
$('#contentDiv').width(noScrollWidth($('#containerDiv')));
Working fiddle.
Try this:
$('#contentDiv').width($('#containerDiv')[0].clientWidth)
For more information about that solution, see this StackOverflow answer.
Another approach I'd try is setting both elements' box-sizing property to 'border-box', and see whether setting your contentDiv's width to 100% then works the way you want.
Now that fewer projects worry about crufty old browsers anymore, 'border-box' can make things easier to work with. Be sure to test multiple browsers on multiple platforms, though, because I'm not sure they all handle scrollbars the same way.

Set initial height of div based on how much space is left inside of parent div

I have 3 divs:
.main_content, .content_top, .content_bottom
.main_content is set to 100% but 100% is not the size of the browser window, it's inside the middle of my page.
.content_top is set at 60% height.
I want to set the height of .content_bottom to the rest of the space available inside .main_content via javascript.
For example, if .main_content was 800px high, and .content_top was 600px high, I want to set .content_bottom to 200px.
This is a simplified example, my situation is not as easy as specifying 40% or leaving the browser to decide. For one, there's currently 46px of padding on .content_top. I'm doing a split screen like interface between .content_top and .content_bottom dragging a bar to resize both. This is mostly working, just having trouble with the bottom portion. Being able to set .content_bottom to a specific height(i.e. 198px) would solve all of my current problems. Happy to elaborate on this example, as well as dig into some actual code, but was hoping there was an easy method for calculating this and was having trouble finding a good example that worked cross-browser, thanks!
Assuming you're using vanilla JavaScript (and not a library), I'd suggest:
​var cBs = ​document.getElementsByClassName('content_bottom');
for (var i=0,len=cBs.length; i<len; i++){
var p = cBs[i].parentNode;
cBs[i].style.height = (parseInt(p.offsetHeight,10) - parseInt(p.getElementsByClassName('content_top')[0].offsetHeight,10)) + 'px';
}​​​​​​​​​​
JS Fiddle demo.
Simple jQuery solution:
$("content_bottom").css({"height": $("main_content").height() + $("content_top").height());

Javascript mobile - calculate element dimensions in pixels based on screen dimensions

I want to calculate the dimensions of certain elements (img, ul, div, etc.) based on screen size. I can't to use percent values. I need pixel values. I also don't want to 'hardcode' everything using media queries and a new set of images for every resolution or screen size.
I thought about making this using screen size. I only need width calculation. So I add the initial width of my images and some initial space between them -> total width, and I then get scaling factor using: screenwidth / totalwidth
Now I scale all of my images and also the space between with this factor.
It's a very simple layout, only a few images and HTML elements. So this scaling should not be expensive.
It would work if the devices gave me reliable width measure for the screen. But depending of the device, I get a different meaning of this value. I'm using screen.width
In some cases screen.width is what the currently width is - in portrait it's a small value, in landscape a large one. But in other ones, width is always the same - the value which is defined as device's width.
So how do I scale my layout according to what's currently screen width in a consistent way with rotation, and without CSS % values? Is this an acceptable way to do layout scaling or am doing no-go?
Edit: I have to add more details after trying Jasper's solution. The images are used in a slider. The slider is basically an UL and each LI contains an image with float:left - so all the images are appended horizontally one after the other. With overflow hidden and stuff only the current slide is visible. Now, the official width of the UL is the sum of the width of all contained LIs. And this means, at least with my current state of knowledge, that I can't use percentage size for the LI elements, because if I did, this will be % of this total width of the UL, which is very large, and I end with immense LI elements/images.
Isn't there any reliable way to get current screen width for all devices ? I already have working code, I only need that the value of screen width is correct.
New update
Look here is a similar approach to what I'm trying to do:
http://ryangillespie.com/phonegap.php#/phonegap.php?
Entry of June 18, 2011 "One Screen Resolution to Rule Them All"
I tried also with exactly that example, copy pasting it in my code. But it doesn't work either. window.outerWidth has the same problems as I'm describing for screen.width (as well as JQuery $('body').width()). It works as long as the device isn't rotated - it initializes well. But at the first rotation, depending of the device, I get problems. In some it works as expected, in others it interchanges the values, so that I get large width in portrait mode and short in landscape, in others it gives fixed width and height all time, in others it doesn't rotate at all....
This is most likely accomplish-able with CSS alone (which is usually good for performance):
img {
width : 100%;
height : auto;
}
That will keep all the image's aspect ratios but re-size them to 100% width. Now that width is set based on the image's parent element(s) width. If you are using jQuery Mobile then the data-role="content" elements have a 15px padding, so to remove that you can just add a container to the image elements that removes the padding:
HTML --
<div class="remove-page-margins">
<img src="http://chachatelier.fr/programmation/images/mozodojo-mosaic-image.jpg" />
</div>
CSS --
.remove-page-margins {
margin : 0 -15px;
}​
And walaa, you've got responsive images without loads of code or overhead.
Here is a demo using a container and not using a container: http://jsfiddle.net/EVF4w/
Coincidentally I found that this works:
$(window).resize(function() {
updateScaling($('body').width());
});
This is always called and passes correct width. As far as I remember it also works with screen.width
In updateScaling I calculate a scalingFactor and adjust my elements.
I tried out responsive CSS, media queries and so on, but at some point it didn't make sense anymore, because I have anyways to recalculate the margin of slider's UL based on current slide and new width - and other stuff which needs script. So I made everything with script.
I removed window.onorientationchange.

How to auto resize text in fixed DIV according to the text's length?

I have a fixed width and height DIV, and I need to put text inside.
Problem is, this text can be in different lengths (letter-wise), so I dont mind to reduce its size once its overflowing.
But how can I do that?
Thanks
You can use window.getComputedStyle if you target modern browsers.
It returns a collection of all real style properties applied to an element.
When you assign your text, you can get its size and compare it with the size of the div. And reduce or increase the font size and measure again.In a few loops you should get the text in the DIV.
Here is a description: https://developer.mozilla.org/en/DOM:window.getComputedStyle
Long story short, you can't do it, since various platform and browsers render fonts differently.
And, there's no cross-browser, cross-platform method to calculate the font's rendered dimensions.
A Javascript "solution" is to check if the div is overflowing, and then bump up its size accordingly, something like
while (div.scrollHeight >= div.offsetHeight) {
div.style.height = (parseInt(fontSpan.style.fontSize) + 1) + 'px';
}

Categories