Wrong div width when getting it with javascript - javascript

I'm trying to get div's width with javascript. Initially div's width is undefined, ie width depends on amount of text on it. Is it possible to get width of this kind of div? I'm trying to do it with following javascript code, but i'm getting width differerent from Chrome console when i'm inspecting div
var mydiv = document.getElementById("error_message");
var curr_width = mydiv.clientWidth;
alert(curr_width);
Thank you for your attention

use offsetWidth
clientWidth is calculated width, offsetWidth is the one in "Chrome inspect element" (i think)
also read the comments :P

While the OP doesn't specify one way or the other, if you happen to have jQuery available, you can always use this:
var curr_width = $('#error_message').width();

I managed to solve the problem! I was trying to create div directly in javascript, without defining div on html body. So inside of tag i've created
<div id="error_message" style="visibility:hidden;"></div>
and it's worked!
Final javascript code is:
document.write("<div id=\"error_message\">Wrong username or password!</div>");
var mydiv = document.getElementById("error_message");
var curr_width = mydiv.offsetWidth;
alert(curr_width);

Related

Determine width of new element in Google Chrome

Is there a robust way to determine width of element tree immediately after creating with document.createElement and placing with something.appendChild ? Element's offsetWidth or getBoundingClientRect works fine in Firefox and IE but not in Google Chrome. It only works with setTimeout but not with zero timeout. 200 milliseconds usually does it. I've read somewhere that accessing offsetWidth triggers reflow but it does not in Google Chrome v47. Maybe it is related to this bug: https://code.google.com/p/chromium/issues/detail?id=290399.
I've never had to use a timeout with clientWidth :
var div = document.createElement('div');
var body = document.querySelector('body');
body.appendChild(div);
var div_width = div.clientWidth;
div.innerHTML = div_width;
<body></body>
Can't you store the width of the element in a variabele using jQuery?
Not sure I understood your question properly but you cannot get the Element width before attaching to the DOM.
Maybe you want to do something like this:
var test = document.getElementById('test').clientWidth;
var div = document.createElement('div');
document.getElementById('container').appendChild(div).innerHTML = 'new element';
http://jsfiddle.net/andreasonny83/5ddtzaf6/
I've figured out it was because of images and I solved it by specifying fixed dimensions. (which is unpleasant for my design)
IE and Firefox do not need it, possibly they load images before returning parent element's width.
Thanks everybody for their help.

javascript - how to get the inner html width of the webpage

I have a few client sites that have a width of about 900px-1000px centered, using javascript how can I find out what the actual width of the document is? I don't need to know the width of the window, just the width that the actual html document is using.
I also can't use any div id's to find it. I know I can use jquery for this, but I'd like to use plain javascript as jquery isn't running on all the sites.
In jquery, I can find this out by using:
$('body').outerWidth(true)
Can someone help?
var body = document.getElementsByTag("body")[0];
var width = body.style.width;
another option:
var body = document.getElementsByTag("body")[0];
var width = body.offsetWidth;
To find width of a document use:
$(document).width();

DOMWindow popup auto resize to contents?

I'm using JQuery and learning as I go, I was just curious is there a way to have a DOMwindow auto resize to its content?
I managed to figure out how to change the parameters to take % width and height instead of px but I'm finding that a dynamic resizing view would utilize my site's purpose better.
Should I be looking into a different type of code to accomplish this?
If you had a containing wrap element, which holds all of the content, and is not set to 100%:
<div id="main_container">
// page contents
</div>
You could now get the dimensions of the containing element and then resize your window to suit.
In jQuery:
$(document).ready(function() {
var myElement = $('#main_container');
var sWidth = myElement.width();
var sHeight = myElement.height();
window.resizeTo(sWidth, sHeight);
})
There are other ways of doing this, if you search thoroughly on this website, you will find your answer. You can use (document).width() and (window).width(), as this answer describes: jQuery(document).width() doesn't include width outside of viewable area

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...

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