How to check really width with "auto" value on css - javascript

I have a loop:
var takediv = document.getElementById('eye');
for(var i=0; i<categories.length; i++){
takediv.innerHTML +=^
'<img alt="'+(categories.length-i)+'" '+
'onclick="changef(this.alt)" '+
'src="mobile/img/pic/'+loc+"/mini/"+categories[categories.length-i-1][0]+'" '+
'style="cursor: pointer;"/>';
}
All images are having this css:
height: 80px;
width: auto;
And finally after loop I need to give the div this css
document.getElementById('eye').style.width
which will be sum of all inner img widhts
It is my first post here so sorry for mistakes.
Please help, and thanks!

You can use several approaches, for example getBoundingClientRect() which returns absolute values for position and width/height:
var width = document.getElementById('eye').getBoundingClientRect().width;
Just note it does not include border or padding, only the inner box.
Then there is getComputedStyle() - this will return a string suffixed with "px" so we also need to parse it using parseInt():
var width = parseInt(getComputedStyle(document
.getElementById('eye'))
.getPropertyValue("width"), 10);
Both returns size in pixels.
And as in #Rudi's answer, there is offsetWidth, and also clientWidth. This won't include margin.

Maybe you're looking for this:
var width = document.getElementById('eye').offsetWidth;

Related

How to reproduce the `.width()` jQuery behavior in pure JavaScript, without another library/framework

I know the method .width() from jQuery returns the element's width without padding, border and margin.
In the accepted answer Table with vertical scroll, in which I can't comment, such method is used to get the width of the td elements of the first row of the table.
One of the jsFiddle in the answer there can be used to see the values returned by the method.
I tried to reproduce the behavior with this piece of code:
let colunas = document.querySelector('.scroll tbody tr:first-child').children;
let colunasWidth = [];
for (let i = 0, length = colunas.length; i < length; i++) {
colunasWidth.push(colunas[i].offsetWidth);//Width/clientWidth
}
I tried the various widths (offsetWidth, width, clientWidth), none gave the same result as jQuery and then I tried to get the border and padding width to subtract from such various widths, but I can't think of a way to get the math or right properties right.
Is there a simple and straightfoward way to do it?
You want window.getComputedStyle and .getPropertyValue
What it does is, it gets the styles used and then gets the actual width value of the element.
Here's a jsfiddle to show you: http://jsfiddle.net/u9d27wno/1/
var jquerywidth = $("#container").width();
var jqueryishwidth = window.getComputedStyle(document.getElementById("container"));
var offsetWidth = document.getElementById('container').offsetWidth;
var clientWidth = document.getElementById('container').clientWidth;
var msg = "offsetWidth: " + offsetWidth + "<br>\n";
msg += "clientWidth: " + clientWidth + "<br>\n";
msg += "jQuery width: " + jquerywidth + "<br>\n";
msg += "jQueryish width: " + jqueryishwidth.getPropertyValue("width") + "<br>\n";
document.getElementById('msg').innerHTML = msg;
//alert(document.getElementById('msg').innerHTML);
Let me know if that's the solution you needed!
You can use element.clientWidth and getComputedStyle together, to obtain teh value you are looking for...
element.clientWidth
The Element.clientWidth property is zero for elements with no CSS or inline layout boxes, otherwise it's the inner width of an element in pixels. It includes padding but not the vertical scrollbar (if present, if rendered), border or margin.
window.getComputedStyle
The window.getComputedStyle() method returns an object that reports the values of all CSS properties of an element after applying active stylesheets and resolving any basic computation those values may contain.
function width(el){
// get element computed styles
let styles=getComputedStyle(el);
// remove the 'px' from the returned values
let paddingLeft = styles['padding-left'].slice(0,-2);
let paddingRight= styles['padding-right'].slice(0,-2);
// substract paddings from value returned by clientWidth, and return value
return el.clientWidth - paddingLeft - paddingRight;
}
// test
let w = width(document.getElementById('test'))
console.log( 'VanillaJS:' , w )
console.log( 'JQuery : ', $('#test').width())
#test{
border:10px solid red;
width:200px;
margin:10px;
padding:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
I'm 200px + <br>
10px padding + <br>
10px border +<br>
10px margin
</div>

How I can get an Image height and divide it by 2 using Jquery

Hi I need to set height of an image to half using j query, So that on click it expands to auto height, How is this possinble please guide.
Currently I used a class with property height: 202px and on click I change that class with another one containing height: auto property, But this does not work fine on responsive views.
So I need to divide the height:auto property by 2, How can i do this with j query, Please guide me with example
Here is my css
.how-we-do .expand-image {
height: auto
}
.how-we-do .expand-image2 {
height:202px ;
}
Here is my jquery code
$('.expand-image').each(function () {
$(this).removeClass('expand-image');
$(this).addClass('expand-image2');
});
You can use .height() to half the height of an on-screen image. .height() takes a function, the second parameter of which will be the current height of the element.
Return this value halved and you have what you need:
$('img').height(function(_,v){ return v/2; });
JSFiddle
Quickfix:
$('img').height() / 2
You can try this.
var cheight = $('.parendiv').innerHeight();
$('img').css({
'height' : cheight + 20
});

jQuery calculating 2 different HTML element attributes (height + margin-bottom)

I'm trying to get the height and the margin-bottom of a element, and count them up. But so far, i can only do this:
var sum = $('div').height() + 25);
That 25 i had to look up myself in the stylesheet at
div {
height: 75px;
margin-bottom: 25px;
}
How can i make this automaticly?
Because when i try:
var sum = $('div').height() + $('div').css('margin-bottom');
It isnt returning any value.
You're probably looking for http://api.jquery.com/outerheight/ which includes the margins, padding and borders (all which count towards the total height, along with the base height). Alternatively, you can use parseInt($('div').css('margin-bottom')) because the value is a css string that looks something like this: 100px. parseInt() would extract the 100 from that css, which is what you want.
In addition, you're kinda doing it wrong in general. Are you looking for the sum of all the heights of all the div elements? Or does your page have only one div?
$('div').css('margin-bottom') will have the px attached. Try and use something like parseInt()
var sum = $('div').height() + parseInt($('div').css('margin-bottom'), 10);
W
There are many 'div' elements in a document(usually).
You need a better selector for the one you want.
Fiddle for value in console.log
<div id="TestId" class="test"></div>
.test
{
height:40px;
margin:5px;
}
var tester = $("#TestId");
var eleHeight = tester.outerHeight();
var marginBottomHeight = tester.css('margin-bottom').replace("px", "")
console.log(eleHeight + parseInt(marginBottomHeight));

Can a DIV's CSS attribute be changed dynamically by javascript just by knowing it's class?

I have this div:
<div class="galleria-info" style="">
<div class="galleria-info-text">
<div class="galleria-info-title" style="">#test</div>
</div>
</div>
And I have this CSS for it:
.galleria-info {
width: 100%;
top: 290px;
left: 330px;
z-index: 10;
position: absolute;
}
What I would like to do is somehow thru javascript change the left attribute of the galleria.info div dynamically so that based on the length of the text for #test i can position the div far enough left to make room for it on screen.
I write different information where the word #test is at in the HTML dynamically and it doesn't have an ID only class.
Any clues or help will be mega-appreciated!
document.getElementsByClassName('galleria-info')[0].style.left = '300px'; // or whatever you want
You have two questions; I have two answers.
Getting by Classname
getElementById() gets the element by its id, getElementsByTagName()[] gets the element by tag name, and to get it by class name, use:
document.querySelectorAll("galleria-info")
Setting the Position
Sorry I used getElementById and getElementsByTagName instead of querySelectorAll.
right Attribute
Wouldn't a right attribute be more appropriate? You could get the width of the body (or container) and subtract however much you want from that instead.
var body_width = document.getElementsByTagName('body')[0].style.width;
var body_width = parseFloat(body_width);
document.getElementById('galleria-info').style.right = (body_width - 600) + "px";
Fixed-Width Font
But, if you are using a fixed-width font, then you can get the length of the string, multiply by the width of each character, and then set style.left to that minus the max distance it can reach (i.e. 300px.)
var str_length = document.getElementById('galleria-info').innerHTML.length;
var str_length = str_length * 10; // Or whatever the fixed width is
document.getElementById('galleria-info-text').style.left = (300 - str_length) + "px";
Wrapper
This doesn't use JavaScript, which, in my opinion, is a good thing because users can disable JavaScript. You can have a wrapper div around the original div that has the following CSS:
#galleria-info-wrapper {
width:300px;
text-align:right;
}
#galleria-info {
text-align:left;
}

jQuery calculate img's real height / width values which coming from server

I am in a situation that; need to calculate image's original width and heigth values when one of them defined 0 on css. I can't change CSS with jQuery, need to solve like this:
Here is example link.
CSS:
img { width:0px; }​
jQuery:
var imgHeight = $('img').height();
alert(imgHeight);//which returning 0 ofcourse
I hope this is possible with less code, thanks,
Try this:
var img = $("img")[0];
alert( img.naturalWidth + "x" + img.naturalHeight );
http://jsfiddle.net/mjaA3/50/
You could clone the element to a new hidden DOM node (I assume you want to hide it here). Then remove the CSS, then measure the dimensions.
var img = $('img'),
imgHeight = img.css("width","auto").height();
img.css("width","0");
alert(imgHeight);
Here is a fiddle. All we do is temporarily set the height to it's automatic value (which is the image's 100% width), grab the height, and reset the image to width:0;.
EDIT: Since you can't manipulate CSS directly, you can change the class:
var img = $('img'),
imgHeight = img.addClass("auto").height();
img.removeClass("auto");
alert(imgHeight);​
And the CSS:
img {width:0;}
img.auto {width:auto;}​

Categories

Resources