trying to acess css properties of a div using javascript [duplicate] - javascript

This question already has answers here:
How do I retrieve an HTML element's actual width and height?
(16 answers)
Closed 10 years ago.
I tried to access the width of a div using javascript,
but every time it is printing NaN no matter what i set it.
I am new to javascript, what is wrong with my code ?
<html>
<head>
<title>hello</title>
<style type="text/css">
#base
{
width:300px;
height:30px;
background-color: black;
}
#scr
{
height:30px;
width:10px;
background-color: red;
}
</style>
<script type="text/javascript">
var magic = function()
{
console.log("inside magic")
var d = document.getElementById("scr");
var b = d.style.width;
console.log(b);
b = parseInt(b);
console.log(b);
}
</script>
</head>
<body>
<div id="base">
<div id = "scr" >
</div>
</div>
<br>
<button onclick="magic()">Magic</button>
</body>
</html>

You can use this function to do that:
function getStyle(el,styleProp)
{
var x = document.getElementById(el);
if (x.currentStyle)
var y = x.currentStyle[styleProp];
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
return y;
}
The explanation of what's going on is here
Note that you must use element's id to access its style property through the function.
If you want to use selectors use document.querySelector() in place of document.getElementById()

you should try
d.offsetWidth
instead of
d.style.width

The code d.style.width returns the width explicitly specified by css while d.offsetWidth returns the computed width.

Related

Javascript cant get document.getElementById('cs') from array

Edit: This is what my code currently looks like. It's still not working.
<head>
<script>
window.onload = myload()
var ids[]
function myload() {
alert("hi")
ids = [document.getElementById('bs'),
document.getElementById('cs'),
document.getElementById('ds')
]
}
function border(){
ids[1].style.border = "9px";
}
</script>
</head>
<body> //elements definded here </body>
I'm trying to write a function that changes the border of a list of images at a certain interval. However, I can't seem to make it work.
I am trying to do the following:
<head>
<script>
var ids = [document.getElementById('a'),
document.getElementById('b'),
document.getElementById('c')]
function(x){
ids[x].border = "9px";
}
</script>
</head>
<body> //elements definded here </body>
but it doesn't run. However, when I run:
document.getElementById('a').border = "9px"
it does work. I'm guessing I'm not calling it properly from the array. What am I doing wrong?
Edit: fixed 'a' twice in the array.
Answering the original question before the function(x) appeared
[1] is the b since JS arrays start at 0
I would expect style.border.
The array has to be defined AFTER the objects have rendered.
If you have the array in a script tag before the elements with ids
a,b,c exist then you will get the ids equal to
[undefined,undefined,undefined]
window.onload = function() { // or addEventHandler OR put script before </body>
var ids = [document.getElementById('a'),
document.getElementById('b'),
document.getElementById('a')
]
ids[1].style.border = "9px solid black"; // the second element
}
<div id="a">A</div>
<div id="b">B</div>
<div id="c">C</div>
Using a function:
var ids=[]; // this is now global in scope
function setIt(idx) {
ids[idx].style.border = "9px solid black";
}
window.onload = function() { // or addEventHandler OR put script before </body>
ids = [document.getElementById('a'),
document.getElementById('b'),
document.getElementById('a')
]
setIt(1); // the second element
}
<div id="a">A</div>
<div id="b">B</div>
<div id="c">C</div>
Fixing your code
window.onload = myload; // removed ()
var ids=[]; // missing an equals
function myload() {
alert("hi")
ids = [document.getElementById('bs'),
document.getElementById('cs'),
document.getElementById('ds')
]
border();
}
function border() {
ids[1].style.borderWidth = "9px"; // just setting border is not enough
}
div { border: 1px solid red }
<div id="bs">A</div>
<div id="cs">B</div>
<div id="ds">C</div>
Arrays in JavaScript are indexed from 0, so doing ids[0].style.border = "9px"; or ids[2].style.border = "9px"; Will give you the desired effect. You'll also want to access the style property on the element (I've fixed that in the code)

Why div DOM object does not have height and width properties [duplicate]

This question already has answers here:
How do I retrieve an HTML element's actual width and height?
(16 answers)
How to get actual CSS property value of an HTML element node? [duplicate]
(5 answers)
Closed 4 years ago.
I am a beginner coder. It is probably very simple, but I tried to find the answer and have not succeeded. My question is why do width and height properties of div object return undefined while they are apparently 100px both?
In this topic is explained how to get .offsetWidth property. But as I understand it is not 100% the same as .width.
window.onload = function() {
var test = document.getElementById("test");
test.addEventListener("click", select);
function select(e) {
var elementID = e.target.id;
var element = document.getElementById(elementID);
var width = element.width;
console.log(element);
console.log(width);
}
}
div#test {
position: absolute;
height: 100px;
width: 100px;
background-color: black;
}
<div id="test"></div>
My answer
Thank you all guys for your answers. They pushed me to find my own simple solution which I hope will be helpful for such beginners as me. The answer is: div DOM object does not have .width and .height property even if you assign them in CSS and they work well. For this purpose it has .style.width and .style.height respectively. But even if you assign them through CSS they will not appear in element.style until you do it purposefully using Java Script. So to get width or height of the div element through JS first of all remove these properties from CSS. You will not need them anymore. Then assign width through element.style.width command and then you can easily get it whenever you want using element.style.width.
CSS
div {
position: absolute;
background-color: black;
}
JavaScript
window.onload = function() {
var test = document.getElementById("test");
test.addEventListener("click", select);
test.style.width = "100px";
test.style.height = "100px";
function select(e) {
var elementID = e.target.id;
var element = document.getElementById(elementID);
var width = element.style.width;
console.log(element);
console.log(width);
}
}
Use offsetWidth and offsetHeight
var test = document.getElementById("test");
test.addEventListener("click", select);
function select(e) {
var elementID = e.target.id;
var element = document.getElementById(elementID);
var offsetWidth = element.offsetWidth;
var positionInfo = element.getBoundingClientRect();
var height = positionInfo.height;
var width = positionInfo.width;
console.log('element', element);
console.log('offsetWidth', offsetWidth);
console.log('width', width);
console.log('height', height);
}
div#test {
position: absolute;
height: 100px;
width: 100px;
background-color: black;
}
<!doctype html>
<html lang="en">
<head>
<title>test</title>
<meta charset="utf-8">
</head>
<body>
<div id="test"></div>
</body>
</html>
I think you need clientWidth and clientHeight.

javascript: get height of div and use it in other div

I want to use javascript to get the height of a responsive div, and use the output in another div.
But I'm no good in javascript at all...
So far I've come up with:
<script language="JavaScript">
var offsetHeight = document.getElementById("myDiv").offsetHeight;
var curr_width = parseInt(offsetHeight.style.height);
offsetHeight.style.height = (offsetHeight);
</script>
<div id="mydiv"></div>
<div id="offsetHeight" style="top:0px"></div>
So what I want is that when I resize the document, the height of mydiv is used for the style="top" value...
Anyone who can help me out? Would be wonderful!
You must be careful about upper/lower letter (mydiv -> myDiv)
You need to add px to set a element's height
var offsetHeight = document.getElementById("mydiv").offsetHeight;
document.getElementById("offsetHeight").style.height = offsetHeight + 'px';
#mydiv {
background:red;
height:150px;
}
#offsetHeight {
background:green;
}
<div id="mydiv"></div>
<div id="offsetHeight" style="top:0px"></div>
Important The script code should be before </body> or wrap it with the listener DOMContentLoaded
try with this below code it may help you
var mydivHeight = document.getElementById("mydiv").offsetHeight;
document.getElementById("offsetHeight").style.height = mydivHeight + 'px';
<div id="mydiv">mydiv</div>
<div id="offsetHeight" style="top:0px"></div>
Use jQuery and let the document load. write your logic inside:
$(document).ready(function(){
//code here
});
Answer here

How can I make the height of a div bigger onclick of a button and then change back to it's original height when click again?

I have a div id="coding" set on height:300px on CSS.
when I click another div id="menu", I want #coding to change it's height to 800px. I managed to do that like this
<script>
function changec() {
document.getElementById('coding').style.height = "800px";
}
</script>
Now, when click the #menu again, I want the height to get back to it's original 300px value. Can someone help? The code is:
HTML
<div id="coding">
<div id="menu" onclick="changec()">≡</div>
...
</div>
CSS
#coding{
...
height:300px;
}
Simple check if the value is set - remove it (then CSS height will take over).
function changec() {
var xDiv = document.getElementById('coding');
if (xDiv.style.height == '')
xDiv.style.height = '800px'
else
xDiv.style.height = ''
}
Demo: http://jsfiddle.net/ygalanter/BLE6N/
one of the solution for your problem is as follows:
First count how many times you click on #menu
now depending on your expectation you can change the javascript as follows
<script type="text/javascript">
var count = 0;
function changec() {
count++;
if(count%2==1)
document.getElementById("coding").style.height = "800px";
else
document.getElementById("coding").style.height = "300px";
}
</script>
Another alternative solution is
<script type="text/javascript">
function changec() {
var currentheight = document.getElementById('coding').clientHeight;
if (currentheight == 300)
document.getElementById('coding').style.height = "800px";
else if (currentheight == 800)
document.getElementById('coding').style.height = "300px";
}
</script>
Not sure why you tagged jQuery since you didn't use it, but still...Considering the possibility that you are willing to use/learn it, I created a jsFiddle for it: http://jsfiddle.net/Tm2Hd/.
CSS:
#coding{
border:1px solid black; /*optional: Keep track of your div's expand*/
height:300px;
}
#coding.larger{
height:800px;
}
JS:
function changeHeight() {
if($('#coding.larger').length>0)
{
$('#coding').removeClass("larger");
}
else
{
$('#coding').addClass("larger");
}
}
HTML
<div id="coding">
<!--<div onclick="changeHeight()">≡</div>
Personally, I don't suggest using divs as clickable objects... Why don't you use buttons instead?
-->
<button onclick="changeHeight()">≡</button>
...
</div>
My solution to your problem is: Create a new class named larger, pointing to your div, and toggle between this and the original whenever you click the button.

Can't Access CSS Selector's Properties from Javascript

Here's a very basic question: why is the finishLoading() function in the code below not able to access the 'opacity' property for the #myStyle CSS selector? The alert doesn't display anything, and I've verified that the 'opacity' property is 'false'.
Thanks very much!
<html>
<head>
<style type="text/css">
<!--
#myStyle
{
opacity: 0.50;
}
-->
</style>
<script type="text/javascript">
<!--
function finishedLoading()
{
alert(document.getElementById('myStyle').style.opacity);
}
-->
</script>
</head>
<body onload="finishedLoading();">
<div id="myStyle">
hello
</div>
</body>
</html>
You can get the values set through class only after their computation.
var oElm = document.getElementById ( "myStyle" );
var strValue = "";
if(document.defaultView && document.defaultView.getComputedStyle)
{
strValue = document.defaultView.getComputedStyle(oElm, null).getPropertyValue("-moz-opacity");
}
else if(oElm.currentStyle) // For IE
{
strValue = oElm.currentStyle["opacity"];
}
alert ( strValue );
The problem is, that element.style.opacity only stores values, that are set inside the element's style attribute. If you want to access style values, that come from other stylesheets, take a look at quirksmode.
Cheers,
I suggest you take a look at jQuery and some of the posts at Learning jQuery, it will make doing things like this very easy.
Opacity should be a number rather than a boolean. Is it working in any other browseR?
this link help
http://www.quirksmode.org/js/opacity.html
function setOpacity(value) {
testObj.style.opacity = value/10;
testObj.style.filter = 'alpha(opacity=' + value*10 + ')';
}
opacity is for Mozilla and Safari, filter for Explorer. value ranges from 0 to 10.

Categories