I have jQuery ajax table, and I need to keep table height while its body isn't fully loaded. This is my code:
var tableHeight = parent.height();
// set parent fixed height so page don't jump up/down during adding
parent.height(tableHeight);
// or: parent.css("height", tableHeight + "px");
$tbody.hide().empty();
// no items loaded
if (rowsData.length === 0) {
this._noItems();
} else {
this._rowAdder(rowsData, actionDisplay);
}
$tbody.show();
parent.height("auto");
"parent" is table object
I know, I can use css attribute "visibility", but for example Mozilla doesn't change css style or table attribute and table displays well. My questions are: Why Chromium ignores configured css style or table attribute height? Can anybody help me, please? Ths ;)
Setting the height attribute is not as easy as setting the width.
In most cases you need to set the html and body heights to 100% if you want a child to know what 100% means.
html,body{
height: 100%;
}
Related
I have a Element with the id="somID";
For Example:
Html:
<div id='somID' ></div>
Css :
#somID{ width:500px;height:500px}
and i have a class named : maximize.
So,
.maximize{width:100% !important; height:100% !important; }
Now dynamically i added the class .maximize to my div #somID
And after that i wanna get the width and height of my #somID by calling with its ID like,
$('#somID').width() or .height()
but i want to take the actual height of element that is defined in its ID but i get the .maximize in result not the height or width that is in #somID.
Any buddy have any idea ? That how to retrieve the height of div#somID if it contains .maximize ??
The problem is, there can be many, many selectors that are applied to a given element, with different specificities. There is no API that allows you to request a property from a selector in CSS - it simply wouldn't make much sense.
Having said that, you can create a hack to solve that issue:
function getOriginalDimensions(id) {
var $a = $("<div>", {id:id});
$("body").append($a);
var width = $a.width();
var height = $a.height();
$a.remove();
return {width:width, height:height};
}
console.log(getOriginalDimensions("somID")); // returns {width:500, height:500}
The above works with your example HTML and CSS.
JSFiddle
This basically creates an element with the same ID, appends it to the body, reads the dimensions and deletes it immediately. This is necessary because the div will have no size if it is just kept as a document fragment and not added to the DOM, because the CSS will not get applied.
In theory you could expand this function to make it work with other selectors.
However bear in mind this is a nasty hack and you should reconsider your approach.
A. Make your measurements and save them as .data attributes of the element :
var $el = $('#somID');
$el.data('original_dims', {
height: $el.height(),
width: $el.width()
}
B. Add class that changes the dimensions of the element :
$el.addClass('maximise');
C. Retrive the original dimensions whenever they are needed
var h = $el.data('original_dims').height;
var w = $el.data('original_dims').width;
I have horizontal layout and it has 5 inline divs. Is there a way in javascript to get the width of the users' viewport then apply it to the each content panel tags width, so it will be 100% in every content panel? I need it to be 100% of the viewport because there are parallax elements inside it
I have tried this css code below but the panels are just stacking on top of each other.
#contentPanel { width: 100%; float: left;}
I really don't know if the questions makes any sense, because I've been up for 16 hours searching and trying to work this out.
It's easy with JQuery:
var fullDiv = $("div");
var viewportWidth = $(window).width();
var viewportHeight = $(window).height();
$("body, html").width(3*viewportWidth);
fullDiv.width(viewportWidth);
fullDiv.height(viewportHeight);
Simple Demo.
You will want to update the divs when the browser is resized probably, currently it only works when it first loads. Read more about .resize().
I am using the following jQuery to giv certain divs with the id's #main, #sidebar, #side-event equal height. On most pages, I am using .hide(); to toggle information within the content section of the site. The problem is when JS caluclates the height of the #main div, it's calculating all of the hidden content as well, which I do not want. How can I alter my code so that the height is equal to the tallest div, and not include the hidden information in the equation? In addition I added the code I am using to hide the information upon page load. Here is my page from the site for referencing the issue. Hoping someone can help me with this issue.
http://shadowfaxdigital.com/cdi/events/mba-essentials-business-design-workshops/
Calculating height:
$("#main, #sidebar, #side-event").addClass("heights");
var highestCol = Math.max($('#main').height(),$('#sidebar').height(), $("#side-event").height());
$('.heights').height(highestCol);
Code used to hide the content in the toggles:
//jQuery toggle
$(".toggle_container").hide();
$("h2.trigger").click(function(){
$(this).toggleClass("active").next().slideToggle("slow");
});
you can add the visible selector, this will check if the element has display:none or opacity:0
var $sfd = jQuery.noConflict();
var cols = $sfd('#main:visible, #sidebar:visible, #side-event:visible');
var maxHeight = 0;
$(cols).each(function(){
$(this).addClass('heights');
maxHeight = Math.max($(this).height(), maxHeight);
});
$sfd('.heights').height(maxHeight);
It's not entirely clear what exactly you're asking for help with. .height() will only include the height of child elements that take up space in the layout. So an item that was hidden with .hide() will be marked display:none and will not be included in the height of any parent elements. But an item that has a zero opacity or visibility:hidden will take up space in the layout and will be included in a parent's height.
In jQuery, you can see if anything is visible with:
$("#main").is(":visible");
Or, you can put it directly into a selector to only include visible items:
$("#main:visible")
So, you could change your code to something like this if you only want to include the visible items in your selector:
var visibleItems = $("#main:visible, #sidebar:visible, #side-event:visible");
var highestCol = Math.max.apply(this, visibleItems.map(function() {
return $(this).height();
}).get());
I ran into this issue aswell today. Googled alot and found this thread. Seems this wasn't properly solved, therefore I'm posting my solution:
My issue was that the height-adjusting script was calculating the heights before the elements were successfully hid with jQuery, I therefore copied my height-equalizing script into a $(document).ready(function() {} );
Like this:
$(document).ready(function()
{
if ($('.sidebar').height() < $('#mainwindow').height())
{
var mainwindowHeight = $('#mainwindow').height();
$(".sidebar").css('height', mainwindowHeight+8+'px');
}
});
This solved it for me.
Hope this helps someone.
I'm busy creating a resizer, but on reloading it first switches from 100% until loading the cookie and setting the width to something fixed:
//set width from cookie, unfortunately we need todo this on docready because #main-container is not done rendering -_-
var width = $.cookie("width");
// Set the user's selection for the left column
if (width != null) {
if (width == "fluid") {
alert("fluid!");
$('#main-container').addClass('width-fluid');
} else {
$('#main-container').addClass('width-fixed');
}
} else {
$('#main-container').addClass('width-fixed');
};
Any ideas?
Thanks,
Dennis
just set the default css property "height" and "width" as 0 inline or in a external css file, then when the cookie is loaded, it will set it to what you want.
ex. of inline default css (before js affects it)
<element style="height:0px;width:0px;" />
I'm assuming you're dealing with a block-level element (image), if not you might want to also set the element to "display:block" so it will respect the height and width.
You can set specific css properties using jQuery with the following :
$("#selector").css("property-name", value);
so for width, you would just use:
$("#main-container").css("width", value);
I'm currently extending the lavalamp plugin to work on dropdown menus but I've encountered a small problem. I need to know the offsetWidth of an element that is hidden. Now clearly this question makes no sense, rather what I'm looking for is the offsetWidth of the element were it not hidden.
Is the solution to show it, grab the width, then hide again? There must be a better way...
The width of an element that has CSS visibility: hidden is measurable. It's only when it's display: none that it's not rendered at all. So if it's certain the elements are going to be absolutely-positioned (so they don't cause a layout change when displayed), simply use css('visibility', 'hidden') to hide your element instead of hide() and you should be OK measuring the width.
Otherwise, yes, show-measure-hide does work.
The only thing I can think of is to show it (or a clone of it) to allow retrieval of the offsetWidth.
For this measurement step, just make its position absolute and its x or y value a big negative, so it will render but not be visible to the user.
You can use the following function to get the outer width of an element that is inside a hidden container.
$.fn.getHiddenOffsetWidth = function () {
// save a reference to a cloned element that can be measured
var $hiddenElement = $(this).clone().appendTo('body');
// calculate the width of the clone
var width = $hiddenElement.outerWidth();
// remove the clone from the DOM
$hiddenElement.remove();
return width;
};
You can change .outerWidth() to .offsetWidth() for your situation.
The function first clones the element, copying it to a place where it will be visible. It then retrieves the offset width and finally removes the clone. The following snippet illustrates a situation where this function would be perfect:
<style>
.container-inner {
display: none;
}
.measure-me {
width: 120px;
}
</style>
<div class="container-outer">
<div class="container-inner">
<div class="measure-me"></div>
</div>
</div>
Please be aware that if there is CSS applied to the element that changes the width of the element that won't be applied if it's a direct descendant of body, then this method won't work. So something like this will mean that the function doesn't work:
.container-outer .measure-me {
width: 100px;
}
You'll either need to:
change the specificity of the CSS selector ie. .measure-me { width: 100px; }
change the appendTo() to add the clone to a place where your CSS will also be applied to the clone. Ensure that where ever you do put it, that the element will be visible: .appendTo('.container-outer')
Again, this function assumes that the element is only hidden because it's inside a hidden container. If the element itself is display:none, you can simply add some code to make the clone visible before you retrieve it's offset width. Something like this:
$.fn.getHiddenOffsetWidth = function () {
var hiddenElement $(this)
width = 0;
// make the element measurable
hiddenElement.show();
// calculate the width of the element
width = hiddenElement.outerWidth();
// hide the element again
hiddenElement.hide();
return width;
}
This would work in a situation like this:
<style>
.measure-me {
display: none;
width: 120px;
}
</style>
<div class="container">
<div class="measure-me"></div>
</div>
Two options:
position the element outside the viewport (ex: left:-10000px)
use visibility: hidden or opacity: 0 instead of hide().
Either way will work as hiding the element but still being able to get the computed width. Be careful with Safari on thi, it's awfully fast and sometimes too fast...
Actual jQuery plugin!
Usage:
console.log('width without actual: ' + $('#hidden').width());
console.log('width with actual: ' + $('#hidden').actual('width'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.actual/1.0.19/jquery.actual.min.js"></script>
<div style="width: 100px; display: none;">
<div id="hidden"></div>
</div>
If you know the element to be the full width of a parent element another approach is to create a recursive method:
es5:
var getWidth;
getWidth = function($el){
return $el.offsetWidth || getWidth($el.parentElement);
}
var width = getWidth(document.getElementById('the-element'));
es6:
let getWidth
getWidth = ($el) => $el.offsetWidth || getWidth($el.parentElement)
const width = getWidth(document.getElementById('the-element'))
What I did was ;
by the time hiding that element, stored its width in its dataset.
It only will work for you if you can hide programmatically.
ie.
When Hiding ;
var elem = $("selectorOfElement");
elem.dataset.orgWidth = elem.clientWidth;
Later when getting ;
var elem = $("selectorOfElement");
var originalWidthWas = elem.dataset.orgWidth;
thats because its hidden via display: none; What ive done in the past is to make a "reciever" div which i use absolute positioning on to get it off the page. Then i load the new element into that, grab the dimensions and then remove it when im done - then remove the reciever when im done.
Another thing you can do is to not use hide(); but to instead set visibility: hidden; display: ; However this means the blank area will be rendered wherever the node is attached.
var $hiddenElement = $('#id_of_your_item').clone().css({ left: -10000, top: -10000, position: 'absolute', display: 'inline', visibility: 'visible' }).appendTo('body');
var width = parseInt($hiddenElement.outerWidth());
$hiddenElement.remove();
I try to find working function for hidden element but I realize that CSS is much complex than everyone think. There are a lot of new layout techniques in CSS3 that might not work for all previous answers like flexible box, grid, column or even element inside complex parent element.
flexibox example
I think the only sustainable & simple solution is real-time rendering. At that time, browser should give you that correct element size.
Sadly, JavaScript does not provide any direct event to notify when element is showed or hidden. However, I create some function based on DOM Attribute Modified API that will execute callback function when visibility of element is changed.
$('[selector]').onVisibleChanged(function(e, isVisible)
{
var realWidth = $('[selector]').width();
var realHeight = $('[selector]').height();
// render or adjust something
});
For more information, Please visit at my project GitHub.
https://github.com/Soul-Master/visible.event.js
demo: http://jsbin.com/ETiGIre/7
Sorry I am late to this conversation. I am surprised no one has mentioned getComputedStyle. (Note this only works if the CSS sets a width value)
Grab the element:
let yourEle = document.getElementById('this-ele-id');
and use the function:
getComputedStyle(yourEle).width
This returns a string so you will have to remove the numbers from the string.
This works even when the element's display style is set to none.
Other articles to read about this includes here at zellwk.com