Skip to content
Advertisement

Can’t get width property with JavaScript

My idea is when I click on the button, the div#x will lose 1% of width. Here is my code:

JavaScript
JavaScript
JavaScript

The blue bar (div#x) is supposed to be shorter 1% every time I click on the left button (section#a). I have check so many times but I still don’t know what problem with my code. I did change some code and I think that problem is in this line lost = document.querySelector('#x').style.width because it seems like it doesn’t return any value which is supposed to gimme 100% width of div#x

Advertisement

Answer

Give this a shot:

JavaScript
JavaScript
JavaScript

This uses clientWidth to get the real width of the element (in terms of pixels), takes 1% off that number, then reset the number back to pixels again.

Explanation:

In your original code, you were trying to access style.width of #x. Since this is a percentage, and not a static value, this will actually return nothing. Luckily, we can get the rendered width of the element with Javascript’s clientWidth property. Using this, we can find the real size of the bar, and calculate the new values from that.

It also might be possible to directly inject the CSS with insertRule – but I don’t see any problems with the clientWidth solution.

EDIT: Use @jwatts1980’s solution from the comments: http://jsfiddle.net/a9okwLd1/1/

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement