Div height doesn't get recalculated on resize - javascript

It works perfectly when I refresh the page, but when I resize it doesn't recalculate the div height.
JSFIDDLE
$(document).ready(function() {
var selectorsArray = ['home', 'about', 'portfolio', 'contact'];
responsiveResize(selectorsArray);
$(window).resize(function(){
var selectorsArray = ['home', 'about', 'portfolio', 'contact'];
responsiveResize(selectorsArray);
});
});
function responsiveResize(selectorsArray){
$.each(selectorsArray, function( index, value ) {
var cntcnter = $('#'+value+' .content-container');
var height = $('#'+value+' .content-container').height();
console.log(height);
cntcnter.css({'height': height+'px', 'margin-top': '-'+(height/2) +'px'});
});
}

The reason it's not working is because on the first run, you set a height to the container. On the second run, it already has a height set so it's always the same value. If the text overflows the container, it's not affecting the new height in this case.
If you want to keep using your code, you need to clear/remove the height you added on the previous run.
You can use this
var height = $('#'+value+' .content-container').css('height', '').height();
Like Chris Empx mentioned, this is easily obtainable with CSS.
Also, you could optimize the code like this fiddle

i wonder why you want to do that with jquery.
i would do that in css.
like that
<div class='container'>
<div class='column col 12'>
<p>Your Inputs here</p>
</div>
<div class='clear'></div>
</div>
then this in css
.container {
margin: 0 auto;
width: 960px;
}
.col-12{
width: 100%;
}
.clear {clear: both;}
.column {padding: 0 .8em; float:left;}
col-6 would be width:50%
col-3 would be width:25%

Related

Run Jquery only when an element is in the viewport

I'm trying to perform the Jquery function below when the element becomes visible in the viewport rather than on the page load. What would I need to change to allow that to happen? I'm using an external JS file to perform the Jquery, so keep that in mind.
Here's a piece of the HTML that is associated with the Jquery function -
<div class="skillbar clearfix " data-percent="70%">
<div class="skillbar-title" style="background: #FF704D;">
<span>Illustrator</span></div>
<div class="skillbar-bar" style="background: #FF704D;"></div>
<div class="skill-bar-percent">70%</div>
</div>
jQuery(document).ready(function(){
jQuery('.skillbar').each(function(){
jQuery(this).find('.skillbar-bar').animate({
width:jQuery(this).attr('data-percent')
},4000);
});
});
I once came across such problem and what I used is waypoints small library.
all you need is to include this library and do:
var waypoint = new Waypoint({
element: document.getElementById('waypoint'),
handler: function(direction) {
console.log('Element is in viewport');
}
})
Using CSS3 transitions instead of jQuery animations might be more performant and simpler. a cheap and nasty way of pushing it out of screen to demonstarate the effect.
There's a couple of things you'll need to do - firstly if you only want the animation to trigger when it's in the viewport then you'll need to check if anything is in the viewport on scroll. Then only update the bars width when it comes into view. If you want the effect to repeat every time it comes into viewport you'll need to set .skillbar-bar's width back to 0 if it's out of the viewport (just add an else statement to the viewport checking if)
I've added a 1000px margin-top and 400px margin-bottom in my example to .skillbar as a cheap and nasty way of demonstrating the effect
(function($){
$(document).ready(function(){
var $els = $('.skillbar'); // Note this must be moved to within event handler if dynamically adding elements - I've placed it for performance reasons
var $window = $(window);
$window.on('scroll', function(){
$els.each(function(){ // Iterate over all skillbars
var $this = $(this);
if($window.scrollTop() > $this.offset().top - $window.height()){ // Check if it's in viewport
$this.find('.skillbar-bar').css({'width' : $this.attr('data-percent')}); // Update the view with percentage
}
});
});
});
}(jQuery));
.skillbar{
margin-top: 1000px;
margin-bottom: 400px;
position: relative
}
.skillbar-bar{
transition: width 4s;
position: absolute;
height: 20px;
}
.skill-bar-percent{
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Scroll down 1000px :)
<div class="skillbar clearfix " data-percent="70%">
<div class="skillbar-title">
<span>Illustrator</span></div>
<div class="skillbar-bar" style="background: #FF704D; width: 20%"></div>
<div class="skill-bar-percent">70%</div>
</div>
This might work for you.
var el = $('.yourElement'),
offset = el.offset(),
scrollTop = $(window).scrollTop();
//Check for scroll position
if ((scrollTop > offset.top)) {
// Code..
}

Div with dynamic header size and content with scroll bar

I am trying to create a container div with a fixed height which has two divs inside, a header div and a content div. The header can grow dynamically and I want the content div to take the rest of the space. The container div should not exceed the specified size and if the content grow to much then content div should scroll.
My current code is as follows but is not working:
<div id="container">
<div id="header">
<button id="btnHeader" type="button">Increase Header</button>MY HEADER</div>
<div id="content">
<button id="btnContent" type="button">Increase Content</button>MY CONTENT</div>
</div>
#container {
height: 300px;
width: 400px;
max-height: 300px;
background-color: grey;
}
#header {
width: 100%;
height: auto;
background-color: blue;
}
#content {
width: 100%;
height: 100%;
overflow-y: scroll;
background-color: red;
}
Example here: http://jsfiddle.net/ep1qab0v/
What is happening is that the content div always stays the same size and hence make the container div to grow. Any ideas?
http://jsfiddle.net/ep1qab0v/3/ ,
I have updated the fiddle with overflow:hidden on the container div. which keeps it the same size. increase in content adds scroll bar to the content div and increase in header pushes the content div down. If I have understood your requirement correctly this is what you are looking for ?
I have made a fiddle with the answer, but I will also try to explain. jsfiddle Example
For that level of dynamic sizing you will have to use javascript. Since the content is scrollable and the header is not, you will have to create an object or function that is called everytime the header size changes. This way you can test the height of the header against the main container, and change the content box to fit.
I created a simple object that you can use to initialize the boxes when the page loads. Also, that you can call every time the page is resized or the header size is changed.
var sizing = {
height: null,
header: null,
content: null,
//Initializes whatever you need
//just cacheing the header and content
//and setting the height restriction
init: function(){
//Set the height of the users window
//you can change this to whatever you want
//but this is dynamic to the browser window
this.height = window.innerHeight ? window.innerHeight : $(window).height();
//Set header and content elements
//for later use
this.header = $('#header');
this.content = $('#content');
this.resize();
},
//Ressize the boxes to fit
//this needs to be called after
// every change to the header
resize: function(){
this.content.css({
height: (this.height - this.header.height()) + "px"
});
}
};
You need to call the .init() to initialize the object when the page loads
$(document).ready(function(){
//Whatever you need to do
//Initialize the sizing
sizing.init();
});
then you can call it from inside events
$('body').on('click', '#some-element', function(e){
//Do some stuff
//Then resize the divs
sizing.resize();
});
Hope that helps!

how to "fix" container element height when scrollbar shows?

I have a horizontal scrollbar which will only show when hover. But the problem is when it shows, it will increase the height of it's container and push the following elements down.
the demo examle.you can see the two div will be pushed down when the scrollbar shows
<div class="wrapper">
<div class="one">
<div class="oneChild">the height is unknown,the height is unknown,the height is unknown,the height is unknown</div>
</div>
<div class="two">I'm two</div>
There are are some rules:
The wrapper and one height can't be fixed,because the *oneChild * content height is unkonwn.And the height of both are all decided by their children.
The scroball only show when hover.you can use js or css to control it's visible.
Any js/css solution will be welcome.
If jquery is an option:
$(document).ready(function() {
height = $('.one').height();
$('.two').css('marginTop', height + 'px');
});
css:
.one {
width: 100px;
border: 1px seagreen solid;
position:relative;
}
.one:hover {
overflow: scroll;
}
.two {
position: absolute;
top:30px;
}
If the child of one will never change, then you could get the height of the element after a height has been set, and then fix it at that height.
var $one = $('.one');
var height = $one.height();
$one.css('height', height);
If the height of the child of one may change, you could fix the height when you are hovering over the element, and set it to auto when you stop hovering.
var $one = $('.one');
var height = $one.height();
$one.on('mouseenter', function() {
$one.css('height', height);
});
$one.on('mouseleave', function() {
$one.css('height', 'auto');
});
You can set the height of the div on hover to the height when the scrollbar isn't there. Assuming that jQuery is ok:
$(document).ready(function() {
var oneHeight = $('.one').height();
$('.one').hover(
function(){ $(this).height(oneHeight); },
function(){ $(this).height(oneHeight); }
);
});
This does add an unfortunate vertical scrollbar, but if you want the vertical position to stay the same, you need to have the vertical bar to see the content that the horizontal scroll bar.
My solution is:add padding-bottom first ,it is as high as horizontal scroball,then when mouseover event happen,padding-bottom set zero.

How to get div's content height

My div has a styling position:absolute, and as a result, it doesn't expand if the content is higher than it's height.
Therefore, I thought that a solution would be if I find what the is the actual content's height, and assign the height to the div with the position:absolute styling.
Any idea how to do it? or maybe an idea how to make an absolute div to expand according to its content.
Thanks in advance!
Element.scrollHeight should do the job.
Here's an awful way to get the height of the container. We're basically cloning the whole div, setting the position so that it has height, checking that height, and then removing it:
$(function () {
var clone = null;
alert( clone = $('.test').clone().css('position', 'static').appendTo(".container").height());
clone.remove();
});
Here's the fiddle: http://jsfiddle.net/vPMDh/1/
It should expand even if being absolute.
check you don't have a height: xxpx
if so, change it to min-height
As you've said "it doesn't expand if the content is higher than it's height." I guess you have a fixed height set on it.. if you do need this for some reason try using min-height instead.
Have a look at this fiddle.
<div class="classname">
Some content....
<p style="clear:both">&nbsp</p>
</div>
use a clearfix hack. heres the link
and add clearfix to you div
example
in your style sheet
<style>
.clearfix:after {
content: ".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
.clearfix {
display: inline-block;
}
html[xmlns] .clearfix {
display: block;
}
* html .clearfix {
height: 1%;
}
</style>
...
and in your div add clearfix the class
<div class="clearfix">
//some html tags
</div>
Thanks for contributing your question. If you use this:
$(document).ready(function(){
var x = $("#container").height();
alert(x);
//if not works then
var y = $("#container").outerHeight();
alert(y);
});
I think it is easy as clean code to find the height of any div if you do not apply the div's height too.
similar solution to #MattDiamant, but with vanilla JS and without creating a clone:
function getDivHeight(posAbsoluteDiv) {
const heightBackup = posAbsoluteDiv.style.height;
posAbsoluteDiv.style.height = 'auto';
const contentHeight = posAbsoluteDiv.getBoundingClientRect().height;
posAbsoluteDiv.style.height = heightBackup;
return contentHeight;
}

Equal Height Columns that Recalculate on Window Resize

The code I have below is supposed to find the height of the largest column (.border) and adjust the height of any other columns found within the .container div to equal it. Unfortunately, I haven't been able to get this code to work as intended so I'm hoping someone wiser than I could can help me out.
It's also worth mentioning that column height should be recalculated and columns resized respectively whenever the window has been resized.
<script type="text/javascript">
$(document).ready(function(){
//Bind the window onresize event
$(window).bind('resize', resizeWindow);
//Call resizeWindow() function immediately to intiially set elements
resizeWindow();
});
function resizeWindow(){
//Find all the container parent objects
$('.container').each(function(){
//Initialize the height variable
var maxHeight = 0;
//Cache the jQuery object for faster DOM access and performance
var $borders = $(this).find('.border');
//Find all the border child elements within this specific container
$borders.each(function(){
//Get current element's height
var thisHeight = $(this).height();
//Check if the current height is greater than the max height thus far
//If so, change max height to this height
if (thisHeight>maxHeight) maxHeight = thisHeight;
});
//Now that we have the maximum height of the elements,
//set that height for all the .border child elements inside the parent element
$borders.height(maxHeight);
});
}
</script>
<div class="container">
<a href="#" class="border">
<div class="column">
<div class="content">asdf</div>
</div>
</a>
<a href="#" class="border">
<div class="column">
<div class="content">asdf</div>
</div>
</a>
</div>
Use the jQuery equalHeights plugin:
http://www.cssnewbie.com/equalheights-jquery-plugin
$('.container .border').equalHeights(); // make all .border the same height
$(window).resize(function(){$('.container .border').equalHeights();});
See: http://jsfiddle.net/rZU35/
This is not exactly a solution to your JavaScript problem. This is a CSS solution, that doesn't need any JavaScript. Using those styles with your markup, both columns will always have the same height:
div.container {
display: table;
width: 100px;
}
div.container > a {
display: table-cell;
border: 1px solid red;
}
Demo
http://jsfiddle.net/wmbcr/
This will work upon resize too, if no fixed width is set.
I think you should provide an height to your DIV not the <a>.
Try this fiddle:
http://jsfiddle.net/ddFtX/1/

Categories

Resources