White Maskers White Maskers - 27 days ago 12
Javascript Question

How I get percentage value instead of pixel value?

if ($C.getElement(".side-bar")) {
$C.setEvent("click",".side-bar",function() {
var element=document.getElementById('navbar');
style = window.getComputedStyle(element);
alert(style.width);
/*if(style.width !== '60px'){
if ( this.childElementCount == 2){
var nodes = this.childNodes;
for(var i=0; i<nodes.length; i++) {
if( nodes[i].className == 'nav nav-second-level'){
if(nodes[i].style['display'] === 'block'){
nodes[i].style.display = '';
}
else{
nodes[i].style.display= 'block';
}

}
}
}
}*/
});
}


In this code I need to be to check the width of navbar ,If width of navbar is not equal-to 6% of total screen then I need to execute the operation (here given an example for width of navbar equal-to 60px).This is happened when I put converted the width in to percentage instead of pixel.Can anyone help me to get the percentage value instead of pixel value?

I'm added the structure of navbar on below



document.getElementById("bttn").addEventListener("click" , function (){
document.getElementById("navbar").classList.add("navbar-after-click");
});

body,html{
width:100%;
height:100%;
}
#navbar{
height:300px;
background-color:blue;
}
.navbar{
width:15%;
}
.navbar-after-click{
width:6%;
}

<div id="navbar" class="navbar">

</div>
<button id="bttn">click me to change the width to 6%</button>




Answer

Probably there is no direct method to convert the value to percentage value.

Though not tested but you can try this way

var yourElement = document.getElementById('someId');
var elemWidth = window.getComputerStyle(yourElement).getPropertyValue("width");
var parent = yourElement.parentNode;
var parentWidth =window.getComputerStyle(parent).getPropertyValue("width");
var calculatePercentage = (100*parseFloat(elemWidth)/parentWidth)+'%';