clientHeight returns zero - javascript

I'm creating the DOM elements dynamically using JavaScript. I need to get height of one div to do the slide down animation. But when i use clientHeight its always returning a 0. offsetHeight also do the same. I'm getting the div when i tried console.log(). So its not because the element is not loaded in DOM. Initially i set style display:none for the div to hide it. Is this the reason for the problem? Please someone help me.
document.getElementsByClassName('myDiv')[0].parentNode.children[1].clientHeight;
I tried the below code to avoid the problem of display:none. Still clientHeight returns 0.
if(obj.style.display == "none"){ // if it's allready hidden we slide it down
obj.style.visibility = "hidden";
obj.style.display = "block";
height = obj.offsetHeight;
obj.style.visibility = "visible";
slideDown(obj,0,height,Math.ceil(height/timeToSlide));
}

Elements styled with display:none will register 0 for its dimensions. Try applying this instead:
div.myClass { position:absolute; left:-999em; }
Same effect, but your div will still have its dimensions.

You need to append in order to know the width... you can use the opacity to hide the content to your needs.
Example
CSS
.hidden {opacity: 0;}
or you can use Chis Hardie displacement solution.

If you are using jQuery you can get the height like this.
$(document.getElementsByClassName('myDiv')[0].parentNode.children[1]).height()

Related

Height auto div to expand height

Please check: http://wixwebsite.seobrasov.com for reference.
My goal here is to achieve a body/wrapper div height according to the content instead of having a scrollbar for a 3500px height body on a 500px content.
I have a one page design with divs sliding in and out. There is a wrapper with overflow hidden and position relative that contains all the divs. Inside that, there are the divs having position absolute and height auto. Inside each div there are the content divs with height aut as well and they correctly expand to fit their content. It is all connected to a javascript that does the sliding. The whole thing only works if I set a fixed height to the wrapper div. Otherwise, having height auto on the wrapper or using javascript to set the wrapper div to the inner div height (which is height auto as well) makes the page not to expand & show any content AT ALL.
The first thing you would think about would be that the wrapper div does not expand height due to position absolute of the inner divs. That is only part of the problem. If I do indeed change the position to relative, it will only show part of the divs.
I have tried using javascript to set the wrapper div to take position from inner divs, but those inner divs also have height auto. And I cannot do the javascript on the content divs as there are more using the same class and having different heights, as they expand depending on content.
So the question that follows is:
Even if I achieve the wrapper div to expand height to its containing divs, wouldn't that height be the height of the biggest div? Since they are all on the same page?
Here is some code:
<div class="content-wrap">
<div class="dhome">
content
</div>
<div class="dabout">
content
</div>
etc.
.content-wrap{
overflow:hidden;
position:relative;
clear:both;
height: 3500px -> aiming for auto
}
.dhome,.dabout{
position:absolute;
right:-200%;
height:auto;
}
So far the only solution I'm seeing to this would be to place the content on different pages but I don't think that I'll manage to do the sliding.
Thanks in advance,
So I got this Javascript that does the animation:
function animate() {
var currentPageI = -1;
var pages = [
$('div.dhome'),
$('div.dabout'),
];
var viewsWidth = 1300;
var showPage = function(index){
if(index === currentPageI){return;}
var currentPage = pages[currentPageI];
if(currentPage){
currentPage.stop().animate({left: -viewsWidth})
}
var nextPage = pages[index];
nextPage
.stop()
.css({left: viewsWidth + Math.max(0,(($(window).width() - 980)/2))})
.animate({left: Math.max(0,(($(window).width() - 980)/2))})
currentPageI = index;
};
showPage(-1);
$('a.dhome').click(showPage.bind(null, 0));
$('a.dabout').click(showPage.bind(null, 1));
$(document).ready(function () {
animate();
});
First of all I have added the suggested Javascript at the end of this one and didn't do anything...after that I have added it into the animation script and used nextPage instead of the wrapper childNodes, and it still didn't do the trick. I will further look into this.
Thank you!
set an ID on the div with class="content-wrap"
var wrapper=document.getElementById(IDcontentwrap);
var childNode, childNodes=wrapper.childNodes, i, l=childNodes.length;
var maxWidth=0, maxHeight=0;
for (i=0;i<l;i++)
{
childNode=childNodes[i];
if (childNode.nodeType==1)
{
if (maxWidth<childNode.offsetWidth) maxWidth=childNode.offsetWidth;
if (maxHeight<childNode.offsetHeight) maxHeight=childNode.offsetHeight;
}
}
wrapper.style.width=maxWidth+"px";
wrapper.style.height=maxHeight+"px";

How would I make div stick to top of screen using this code?

The code below is test code I'm using. The blue bar is supposed to stick to the top of the screen when it reaches the top.
This works on my browser, but the reason I'm here is because when it sticks to the top, it all of a sudden becomes smaller. As you see the blue bar starts with a full width across the container, but on my computer/browser, after it sticks to the top, the div shrinks to just the size of the text.
To make matters worse, I cannot reproduce the problem on jfiddle, because in jfiddle it doesn't work at all! (The images are just there to create a scroll).
Here is the jfiddle
Here is the jquery:
var titlePosition = $('.title').offset().top;
$(window).scroll(function () {
var scrollBar = $(this).scrollTop();
if (scrollBar > titlePosition) {
$('.title').css("top", "0px");
$('.title').css("position", "fixed");
} else {
$('.title').css("position", "relative");
}
});
Try this code:
Fiddle
CSS:
.title {
font-size:200%;
background-color:blue;
width:100%
}
Update your code:
if (scrollBar > titlePosition) {
$('.title').css("top", scrollBar+"px");
$('.title').css("position", "fixed");
} else {
$('.title').css("position", "static"); //otherwise it will still get that top value and cause unwanted position;
}
Just add this css:
.title {
...
width: 100%; /*This does the trick*/
}
Here you have it working: http://jsfiddle.net/edgarinvillegas/yPWAC/3/
Cheers
Set left to 0 as well. Additionally, some optimizations.
I prefer appending/removing classes to put all your CSS in your stylesheet. Saves you from problems later on when the code gets huge (who would be looking for CSS in JS files anyway?).
Also, cache objects. Everytime you fire scroll, your code fetches every single .title in the DOM and generates a jQuery object. Not very optimal. Instead, get all .title and just do the modifications on each scroll.
CSS:
.title.fixed {
position:fixed;
left:0;
right:0;
top:0;
}
JS:
var titlePosition = $('.title').offset().top;
var win = $(window);
var title = $('.title');
win.scroll(function () {
var scrollBar = win.scrollTop();
if (scrollBar > titlePosition) title.addClass('fixed');
else title.removeClass('fixed');
});
As for your non-working fiddle, you forgot to include jQuery. That should be found on the top left.
Try giving z-index:999 or, using jQuery - $('.title').css("z-index", "999");
Rest looks ok.
var titlePosition = $('.title').offset().top;
.top is not a function. offset() returns an object containing the properties top and left
Replace with:
var titlePosition = $('.title').offset();
You can now access the properties like so:
titlePosition.top or titlePosition.left
reference: .offset() http://api.jquery.com/offset/
Thanks for all the feedback.
Even though it helped improve, in the end the div was still resizing. Fixing the width to specific values was not responsive enough.
I finally stumbled upon a solution, based on all the advice:
http://jsfiddle.net/yPWAC/8/
var titleWidth = $('.title').width()
/*then after the div is fixed I change the width */
$('.title').css("width",titleWidth);
I made jquery hold the original width of the div, then change the width of the sticky div to whatever that value is.
For some reason, even if I defined the original width in CSS, the new sticky width would still come out a different size in the browser. So this method gives it the same width as the original (whatever it may be)

Using javascript I want to change the size of images which are in particular div tag

In an HTML document there are few div tags with ids DIV1, DIV2
In DIV1 there are 2 images. in DIV2 there is only a single image. Using javascript I want to change the size of images which are in DIV1 to 100px. How can I specify images which are in that particular div tag?
Assuming that those are ids:
#div1 img {
width: 100px;
]
Or, if you prefer (for some reason, though you should use CSS for this), you can use JavaScript:
var div1Images document.getElementById('div1').getElementsByTagName('img');
for (var i = 0, len = div1Images; i < len; i++){
div1Images[i].style.width = '100px';
}
The reason I set only one dimension (width) is that this way the image's height will be automatically adjusted to fit maintain the natural aspect-ratio.
document.querySelectorAll('.div1 img')
This will give you a NodeList object of all of the img elements in <div class=div>` (obviously change as needed). You can iterate over it like a normal array and update the element widths to whatever you want .. even 100px!
If you want to use jQuery its should be as simple as:
$(document).ready(function () {
//select images and adjust height & width however you want, or use just width to scale proportionately
$('#div1 img').width('100px');
$('#div1 img').height('100px');
});
Here's a jfiddle example: http://jsfiddle.net/t9pUL/4/
However, I agree with David Thomas that you should probably use css for this unless you have a real reason to use javascript.

How to make a DIV visible and invisible with JavaScript?

Can you do something like
function showDiv()
{
[DIV].visible = true;
//or something
}
if [DIV] is an element then
[DIV].style.visibility='visible'
OR
[DIV].style.visibility='hidden'
Let's assume you do not use a library such as jQuery.
If you do not already have a reference to the DOM element, get one using var elem = document.getElementById('id');
Then you can set any CSS property of that element. To show/hide, you can use two properties: display and visibility, which have slightly different effects:
Adjusting style.display will look as if element is not present at all ("removed").
elem.style.display = 'none'; // hide
elem.style.display = 'block'; // show - use this for block elements (div, p)
elem.style.display = 'inline'; // show - use this for inline elements (span, a)
or style.visibility will actually make the div still be there, but be "all empty" or "all white"
elem.style.visibility = 'hidden'; // hide, but lets the element keep its size
elem.style.visibility = 'visible';
If you are using jQuery, you can do it even easier as long as you want to set the display property:
$(elem).hide();
$(elem).show();
It will automatically use the appropriate display value; you do not have to care about the element type (inline or block). Additionally, elem can not only be a DOM element but also a selector such as #id or .class or anything else that is valid CSS3 (and more!).
You can use visibility or display but you have to apply changes to the div.style object and not the div object itself.
var div = document.getElementById('div_id');
// hide
div.style.visibility = 'hidden';
// OR
div.style.display = 'none';
// show
div.style.visibility = 'visible';
// OR
div.style.display = 'block';
You can use the DOM functions: setAttribute and removeAttribute.
In the following link you have an example of how to use them.
setAttribute and removeAttribute functions
A quick view:
hide: document.getElementById("myDiv").setAttribute("hidden","");
unhide: document.getElementById("myDiv").removeAttribute("hidden");
as of November 2022 browser support for CSS revert value is 94.56% (https://caniuse.com/?search=revert) so if for hiding you use
elem.style.display = 'none'; // hide
for visibility use
elem.style.display = 'revert'; // show
this posolite doesn't care about element type
Note: The revert keyword is different from and should not be confused
with the initial keyword, which uses the initial value defined on a
per-property basis by the CSS specifications. In contrast, user-agent
stylesheets set default values on the basis of CSS selectors.
For example, the initial value for the display property is inline,
whereas a normal user-agent stylesheet sets the default display value
of <div>s to block, of <table>s to table, etc.
revert
You can use opacity which is similar to visibility but allow to smooth transition and control other parameters like height (for snippet simplicity I put js logic in html directly - don't do it in production code)
.box { width:150px; height: 150px; background: red; transition: 0.5s }
.hide { opacity: 0; height: 10px}
<div id="box" class="box"></div>
<button onclick="box.classList.toggle('hide')">Toggle</button>
Make Invisible using CSS
#div_id {
/*height: 400px;*/
visibility:hidden;
}
Make Visible using Javascript
document.getElementById('div_id').style.visibility = 'visible';
Use 'hidden' attribute of DOM element:
function showDiv(isVisible)
{
[DIV].hidden = !isVisible;
}
ID is the name of your div. Make sure to have runat="server" in the Div.
document.getElementById('<%= ID.ClientID %>').hidden = false;
document.getElementById('<%= ID.ClientID %>').hidden = true;

can not get the width of the html element

I create an element using js,and I have imported the related css,however I can not get the width of the element,this is the code:
css:
#mainDiv{
position:absolute;
width:500px;
height:500px;
}
js:
var mainDiv=document.createElement("div");
mainDiv.setAttribute("id","mainDiv");
document.body.appendChild(mainDiv);
//now I want to get the width of the 'mainDiv'
var wd=mainDiv.style.width;
console.info(wd);
However the value of the 'wd' is always ''.
I wonder why?
Using the firebug,I found that the width of the 'mainDiv' is 500px.
But why I can not get the value in the js?
I do not want to set the width and height of the 'mainDiv' in the js like:
mainDiv.style.width='500px';
I want to set the size in the css.
Any idea?
try
var wd=mainDiv.clientWidth;
Use mainDiv.offsetWidth .
Hope this helps.
Listen, this is an awful answer, but just use jQuery.
If you did this would be as simple as:
var width = $('#mainDiv').width(); // width has the value 500
Docs: http://api.jquery.com/width/
In order to get the actual width of a DOM element you must use offsetWidth.
From W3Schools:
offsetWidth: Returns the width of an element, including borders and padding if any, but not margins
This example should work:
var mainDiv=document.createElement("div");
mainDiv.setAttribute("id","mainDiv");
document.body.appendChild(mainDiv);
var wd=mainDiv.offsetWidth;
console.info(wd);
It's because the element is not yet rendered. I know it's awful, but you should delay reading the width a bit:
var mainDiv=document.createElement("div");
mainDiv.setAttribute("id","mainDiv");
document.body.appendChild(mainDiv);
setTimeout(100, function() {
console.info(mainDiv.style.width);
});
You cannot get the width because you are trying to get it from the style. Sorry went into train, basically because you are not setting the style element but rather defining a class - JavaScript can't read the value from the element.

Categories