+ 2

[SOLVED]Strange return value from .css("width")

I am using jQuery for a little project of mine, and before I start, I know the difference between .width() and .css("width"). Here is the code: https://code.sololearn.com/Wh1mfm0gGXlY . When you click the button, you will see in the console the data for the xp bar (the one below the moving progress bar). Specifically, its width numbers using jQuery's .css("width") calls. I am trying to extract the percentage, which should just be parseInt($(element).css("width"), 10), but it is returning the pixel numbers as if I am using .width(). The code in question starts at line 40 and goes to line 67. Apparently it will work using the vanilla JavaScript calls: element.style.width. What is going on here? BONUS: Why is using "height: 100%" for the .buttonContainer class in the css causing the button to extend beyond the screen height? It only happens in SoloLearn's environment, not on my local host.

1st Jul 2018, 12:44 AM
Zeke Williams
Zeke Williams - avatar
4 Réponses
+ 4
jQuery css function could not return percentage value, the different between. width() and .css("width") is .width() return a pixel number, whereas .css("width") return a string with dimension px. The easier way is to use vanilla Javascript. style.width. Just because the code has been included jQuery lib, it's not necessary we must use jQuery function all the times.
1st Jul 2018, 1:51 AM
Calviղ
Calviղ - avatar
+ 2
This is working fine on my playground .buttonContainer { background-color: grey; height: 100%; } Try to add box-sizing: border-box;
1st Jul 2018, 1:58 AM
Calviղ
Calviղ - avatar
+ 1
It returns the string in px? Haha I even read the documentation, but it always used "12px" or something similar as an example, but I guess I didn't see the place where it said it ALWAYS returned the string in pixels. Thanks for the answer Calviղ ! Can you solve my bonus problem by chance?
1st Jul 2018, 1:57 AM
Zeke Williams
Zeke Williams - avatar
+ 1
Calviղ , you are a real hero. it worked! Thanks a bunch 😄
1st Jul 2018, 2:00 AM
Zeke Williams
Zeke Williams - avatar