How can i dynamically update DIV block height? - javascript

I have 2 divs. 1st div should automatically change own height if 2nd div height was changed.
var height = jQuery('#leftcol').height();
height += 20;
jQuery('.rightcol-botbg').height(height);
There is no ability to change HTML markup :(
I have many DHTML layout changes, so I can't run prev. code anytime.
I want to run it dynamically. I need to do something like event/trigger.
I tried to use jQuery('#leftcol').resize(function(){}) or jQuery('#leftcol').change(function(){}). but it doesn't work. (resize triggers when window size changes.)

When does your 1st div change ? Whatever triggers that should get the new div height, add 20 to it and set the height of the other div. Can you post some code samples ? If the size changes happen really frequently, a timer/interval that repeatedly checks one size and set's the other should also work, but this is less efficient.

I would monitor the other div using an interval then update accordingly
setInterval(function(){
var height = $('#leftcol').height();
if(height != $('#leftcol').data('oldHeight'))
{
$('.rightcol-botbg').height(height+20);
$('#leftcol').data('oldHeight',height);
}
},500)
(untested)
The above code checks for changes in height every 0.5 seconds, then updates .rightcol-botbg;

I don't understand JQuery, but seeming as this question is tagged Javascript I'll give you a Javascript solution
document.getElementById("yourDivID").style.height = "300px";
Edit - You want to know when the height of the div has changed?
I don't know if there is a better way for that, but I would approach it with a function:
function changeBlockHeight(divID, newHeight)
{
document.getElementById(divID).style.height = newHeight + "px";
blockHeightChanged(divID);
}
function blockHeightChanged(divID)
{
alert("Div " + divID + " has been changed in height!");
}
Somewhere in your code:
<div id="testBlock"></div>
<button onlcick="changeBlockHeight('testBlock')">Test</button>
Every time you change the blocks height, blockHeightChanged() is called.

well there is not any generic triggers for an element resize.
what is the cause of div's size change at your case? you can check your heights righta after or in that cause.
only alternative that i can think of is setting up a timer with setInterval and check both div sizes every once in a while.
var myInterval = self.setInterval("myCheckFunction()",1000);
function myCheckFunction() {
jQuery('.rightcol-botbg').height(jQuery('#leftcol').height());
}

Using an interval is not very browser friendly.
If you have a setup like this:
<div id="content">
<div id="tree">should be full height</div>
<div id="data">this one is half the height</div>
</div>
You could easily do this with css. I'm not sure if this is the case...
Otherwhise the solution proposed by Tom Gullen is the best one.

Use .bind() to create a custom event type, and then trigger that event using .trigger().
Here is a fiddle with an example (a bit contrived, but I think you will get the idea)

Related

Can't change the div-height vis timeline

I'm using vis.js-timeline and would like div with classes "vis-panel vis-background vis-vertical" to be about 600px high. However, the height (at the moment 198px) seems to be set programmatically and I haven't managed to change it.
The user asking the question answered h(im|er)self in a comment earlier; however, it may be useful as an actual answer.
You can do options = {height: '600px'}; and then in the when you create it, pass in the options. For example:
var visObj2d = vis.Timeline(container, dataset, options);
I found this vis documentation to be particularly useful.
Programmatically, you could try to override the height of the css class.
If you use the jQuery library, you could try to overwrite as follows:
var interval = 2000; // 2 seconds.
var height = "600px"; // New heigth.
setTimeout(function () {
$(".vis-panel.vis-background.vis-vertical").css({"height": height});
}, interval);
Why:
Programmatically, in a certain time you can manipulate the properties of a HTML tag, in this case, a div.
This code adds an attribute "style" to the div tag with class "panel vis-vis vis-background-vertical", after 2 seconds the normal rendering of vis timeline. You can increase or decrease the time as you need.
style="height: 600px;"
I hope this helps you.

Link two HTML divs' dimensions to each other?

If I have div A and div B, is there a way to say A.width = b.width = MAX(a.width, b.width) ? That is, whichever has the largest inner content would dictate how large both are.
The actual problem I'm trying to solve is with columns - left, middle, and right. I want the left and right to be the same fixed width (but this could vary depending on their content).
It is not possible to use CSS to achieve this. However, if there is a way to do it with a JS-based solution. Here I am using jQuery. Let's say you have two divs, with classes a and b respectively.
$(function() {
function equalizeSize($ele) {
if($ele.length > 1) {
// Let CSS automatically calculate natural width first
$ele.css({ width: 'auto' });
// And then we fetch the newly calculated widths
var maxWidth = Math.max.apply(Math, $ele.map(function(){ return $(this).outerWidth(); }).get());
$ele.css({ width: maxWidth });
}
}
// Run when DOM is ready
equalizeSize($('.a, .b'));
// Run again when viewport has been resized, which **may** affect your div width.
// This is optional, but good to have
// ps: You might want to look into throttling the resize function
$(window).resize(equalizeSize($('.a, .b')));
});
See proof-of-concept fiddle here: http://jsfiddle.net/teddyrised/N4MMg/
The advantages of this simple function:
Allows you to dictate what elements you want to equalize widths with.
Uses the .map() function to construct an array, which we then use Math.max.apply to get the maximum value in the array
Forces automatic calculation of width when the function first fires (especially when resizing the viewport)
Allows you to call to recalculate the size again, using the handler equalizeSize() when you change the content in the divs... you can call the function again, say, after an AJAX call that appends content to either element.
It is not very clear what you want from the description. but I can rewrite your code this way.
var properWidth = Math.max($("#a").width(), $("#b").width());
$("#a").css("width", properWidth + "px");
$("#b").css("width", properWidth + "px");
I am not sure if it is this kind of solution you want.
I'm not sure there is a way to do it like that. But why not make a default function to set the size:
function changeSize(w, h)
{
A.setAttribute('style', 'width:'+w+'; height:'+h);
b.setAttribute('style', 'width:'+w+'; height:'+h);
}
Working fiddle: http://jsfiddle.net/kychan/ER2zZ/

Script's function works correctly on resize but not on document.ready

I have a function that corrects and adapts the size (and vertical alignment) of three fluid columns with text and images.
The script, while not polished/efficient yet, works exactly as expected but sometimes(?) fails at the beginning.
The functions is the following:
var resetHeight = function(){
var maxHeight = 0;
$(".same-height-col").height("auto").each(function(){
maxHeight = $(this).height() > maxHeight ? $(this).height() : maxHeight;
}).height(maxHeight + 25);
var maxTextSize = 0;
var tempHeight;
$(".same-height-col").each(function(){
tempHeight = $(this).find(".links-text").height();
maxTextSize = tempHeight > maxTextSize ? tempHeight : maxTextSize;
});
var topMargin;
$(".same-height-col").each(function(){
topMargin = (maxTextSize - $(this).find(".links-text").height()) + 25;
$(this).find(".links-image").css("margin-top",topMargin);
});
}
The I call it twice:
$(document).ready(function() {
resetHeight();
$(window).resize(function() {
resetHeight();
});
});
The problem is that many times when I load the page, I see this:
That doesn't happen consistently, but it does happen pretty often, but as soon as I resize the window the script works exactly as expected:
So where could the mistake be?
The script is called for sure even at the beginning, if I put an alert in the function, and just load the page (with no resize), the alert pops up.
When you calculate the maxHeight value, you reset all the inline heights that were set in the previous resetHeight call by doing $(".same-height-col").height("auto"). However, you don't reset the margin-top properties that were added to the links-image elements.
This means that the second time that resetHeight is called (and all subsequent times), the maxHeight calculations will be different. To make sure the results are the same each time, you need to reset the margin-top property on the links-image elements before doing the calculation.
$(".same-height-col .links-image").css("margin-top","");
$(".same-height-col").height("auto").each(function(){
maxHeight = $(this).height() > maxHeight ? $(this).height() : maxHeight;
}).height(maxHeight + 25);
You may also want to make that height maxHeight+50 rather than maxHeight+25 if you think the result of the layout after the resize looked better than the intial layout on load.
As i understand your issue, you should set attribute width and height of images and use the document ready handler:
HTML for all images in .links-image DIVs: {width/height/alt attributes should always be specified for image when possible}
<div class="links-image" style="margin-top: 53px;">
<img src="img/list.png" width="210" height="92" alt="">
</div>
JS code:
$(document).ready(function() {
$(window).resize(resetHeight).trigger('resize');
});
I’m starting with the premise that you want the box content components — the title, the subtitle, and the image — vertically aligned across all the three boxes. If this is not true, just ignore this answer.
While I can’t spot the issue in the code at hand, I would try to approach it another way, without JS: clearfix the columns and fix the height of the components: let’s say I expect titles to be one line of text, subtitles three lines, and images are already fixed-height.
The fixed height will give you vertical alignment, and the clearfix will take care of the column height.

I can't get a Div's width using element.style.width. Do I have to use element.clientWidth instead?

I think I'm going mad!
I'm starting to write a little exercise for myself where I am going to have some divs that I can drag on the rightborder to increase or decrease the Div width. I also have a container Div that has a set width and I'm going to use this to determine a percentage - basically I'm going to be making some kind of bar-chart / histogram that you can edit.
I'm started writing my code and I thought I'd just make sure I could output the percentage.
Here's the perliminary code....
<style>
#container{width:500px;}
#dragDiv{border:1px solid #000;background-color:pink;width:100px;height:100px;}
</style>
</head>
<body>
<div id="container">
<div id="dragDiv"></div>
</div>
<script>
function dragOneSide(innDiv, outDiv){
if(document.getElementById(innDiv) && document.getElementById(outDiv)){
var iDiv = document.getElementById(innDiv),
oDiv = document.getElementById(outDiv);
// write out the width as a percentage
var iDivWidth = parseInt(iDiv.style.width),
oDivWidth = parseInt(oDiv.style.width);
//alert(document.getElementById("dragDiv").style.width);
iDiv.innerHTML = ((iDivWidth / oDivWidth) * 100);
}
}
window.onload = function(){
dragOneSide("dragDiv", "container");
}
</script>
Now the value in the iDiv was NaN? I found that rather odd. When trying to alert width I was getting a blank, literally an empty string! Rather odd I thought, especially as I wasn't trying to do anything complicated. I used firebug, set a breakpoint and observed the watch window. There was no value for the Div's width. I then put an inline style on the DIV like so...
<div id="container">
<div id="dragDiv" style="width:300px;">Hello World</div>
</div>
and low and behold I was now getting a value for the item! Now I don't like inline styles (who does) however I've never had this problem before and I've been using JavaScript and HTML for years - has anyone got an explaination for this? To retrieve the width not set by CSS do I have to use a different property like clientWidth?
Ps. I haven't included any of the dragging code yet so please don't point that out.
The call to style.width retrieves the style value, which isn't set.
http://jsfiddle.net/EC2HR/
See this example. Yes, you want to use clientWidth in this case.
The simplest way is to use offsetWidth property:
var iDivWidth = parseInt(iDiv.style.offsetWidth),
oDivWidth = parseInt(oDiv.style.offsetWidth);
style.width is a DOM api which returns the width of an element when it's set inline or via the element.style.width = n + "px";
So that it reacts the way you describe it is as designed.
The offsetWidth like ioseb refers to is a DOM api call which returns the amount of horizontal space an element takes up.
Beware of the many inconsistencies between browsers .
PM5544...

Adjusting elements based on scrollHeight using JQuery

Here's what i have so far:
function loadOff(){
$(document).ready(function(){
$("#eLoader").ajaxStop(function(){
$(this).hide();
$("#eventsContent").show();
var h = document.body.scrollHeight;
$("#bodyBackground").css("height",h+100+"px");
$("#sidePanel1").css("height",h-105+100+"px");
$("#bottom").css("top",h+100+"px");
});
});
}
This is a callback function for a JQuery ajax function, basically what is does is when all ajax is finished .ajaxStop() it hides the loader then shows the content.
The problem i am having is adjusting bodyBackground, sidePanel, and bottom to fit the content. I dont care to have it elastic and retract for short content at this point, i would just like it to extend to proper positioning based on content length.
All divs are absolutely positioned. The numbers in the function are broken down simply to make it easy to explain. -105 is the offsetTop of that element and +100 is the margin between the end of the content and the elements.
if there is a better, more efficient way to achieve this outcome, please, do tell.
Thanks.
Based on your code, the only thing you ought to see is the top 105px of #sidePanel1. Is that your intent? (h = the bottom of the window, according to your code.)
Sticking with the JQuery patterns, you would use
var h = $(window).height();
Maybe you're looking for this instead of the browser window's height? It will get the height of the content element.
$("#eventsContent").outerHeight();

Categories