Get The Height And Width Of Window In JQuery For Resopnsive Web Design

Why do We need to Get the Window Height and Width in Responsive Web Design ?

Now-a-days responsive web design becomes minimum requirement while developing or designing a website. In today's market everyone wants his website to get render nicely in any type of device by keeping the reason in mind of the usage of mobile/tablet devices in business process.

Mobile devices have become an unavoidable part of our life. We are using those for almost everything like browsing, internet surfing, online shopping and also for all other important works like applying for a job, filling up any application for admission, Tax payment, for mobile recharge etc. So by keeping this vast use of mobile devices in mind it has became a must for all the website depending companies or organizations to serve their clients with the best user experience irrespective of the device they are using.

So, in order to make a website responsive you need to calculate the height, width of the browser in every step a user resizes the window.

Here is a simple way to find the width and height of a window when it got resized.

Let's See How to get The Window Height and Width in Jquery

There is a feature in JQuery through which you can get the width and height of the window or document.



But the problem with that thing is when the page loads for the first time you can get those values but lets think if the user resizes his browser then what will happen this website should render accordingly.

For doing so you need to check the height and width in every attempt user resizes the browser.

JQuery provides a method $(window).resize(), which get called when the the user is trying to resize the window. So you can get the height and width in every resolution of the window automatically.

Below I have taken two div to show the size of the window initially and after it gets resized.
  <div id="divInitial"></div>
  <div id="divResize"></div>
Then I have written the below JQuery to fetch the width and height every time user resizes his window.
 <script type="text/javascript">
        $(document).ready(function () {
            $("#divInitial").text("Initial Window width: " + $(window).width() + ", height: " + $(window).height() + ".");

            //Event to handle resizing
            $(window).resize(function () {
                var width = $(window).width();
                var height = $(window).height();
                $("#divResize").text("Window width: " + width + ", height: " + height + ".");
This will write the height and width in the div when user tries to resize the window. So you can assign the CSS to the controls accordingly for making your website responsive.

Live demo

** Click on the Live Demo link above to see the example in jsfiddle and go on resizing the window and see what happens.

Happy Coding...

No comments:

Post a Comment