I am trying to write a JavaScript function to get the current browser width.
I found this one:
console.log(document.body.offsetWidth);
But its problem that it fail if the body has width 100%.
Is there any other better function or a workaround?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Update for 2017
My original answer was written in 2009. While it still works, I’d like to update it for 2017. Browsers can still behave differently. I trust the jQuery team to do a great job at maintaining cross-browser consistency. However, it’s not necessary to include the entire library. In the jQuery source, the relevant portion is found on line 37 of dimensions.js. Here it is extracted and modified to work standalone:
Original Answer
Since all browsers behave differently, you’ll need to test for values first, and then use the correct one. Here’s a function that does this for you:
and similarly for height:
Call both of these in your scripts using
getWidth()orgetHeight(). If none of the browser’s native properties are defined, it will returnundefined.