Getting started with responsive websites and JavaScript

In this post I’m going to describe two basic web pages I’ve been working on:

  • a basic responsive page, and
  • a responsive page that uses JavaScript to detect the current size of the screen.

My goal here is to use basic HTML, CSS and JavaScript – no js libraries – to help myself learn JavaScript and responsive data visualization techniques. That said, I’m not an expert, and the examples should be considered with that in mind. Please comment at the end of the post if you have better, or different, ways of doing the same thing.

A basic responsive page

First, credit where credit is due: this page draws directly from the example website developed in Clarissa Peterson’s book Learning Responsive Web Design. I found this book to very helpful in getting started. So, what does the resulting responsive page look like? You can see it in action here: basic responsive page and all of the code is available in this gist: gist for basic responsive page. Try resizing your screen to see how the page adapts to large vs small screens. In particular, for

  • large screens the aside element should float to the right of the article element, whereas for
  • small screens the aside element should be below the article element and occupy the full width of the screen.

How does this work? If you look at index.html for the basic responsive page, the code is really pretty simple. All of the magic happens in a few places:

  • viewport: the meta tag, in the index.html header section, sets the viewport using sensible values for the width and initial scale.
  • media queries: the media query (see lines 58-72), found at the bottom of main.css for the basic responsive page, changes the article, aside and footer properties for larger screens– changing widths, making the aside float right, etc. The default properties (for small screens) are set at the top of the css file and are overridden when the width of the screen is greater than the specified 38em. You can play with this value to change the breakpoint, the width at which different large-screen style takes effect. Of course, more than one media query is allowed, so the control of layout for different screen sizes can be controlled with great specificity. We’ll stick with one media query in this case, keeping things simple.

The only other parts to mention, briefly, are the reset.css by Eric Meyer – see Eric Meyer’s reset.css for more information. Basically, this css file zeroes-out style settings that are later set in the main.css file. Finally, there is the fullpage div, which sets a maximum width and auto margins. These settings keep the page from getting too wide and centers the content on large screens, like a big monitor.

So, that’s it for the basic responsive page. Do you have another way to do things like this? Please comment below and provide links!

Using JavaScript to find screen and element dimensions

Next, we add a little JavaScript to figure out how large the screen and various HTML elements are as the screen is resized. A live version of the page is here: responsive page with js– again, try resizing the page to see how the dimensions of the elements adjust. All of the code is available in this gist for responsive page with js.

So, how does this example work? As you might expect, much of this example is exactly same as the basic responsive page discussed above. A JavaScript file, main.js for responsive page with js, is added with all of the code and is linked in the index.html for responsive page with js on line 59. In addition, a few div elements have been added to the index.html as place-holders for writing the dimensions of the various HTML elements. For example, see <div id="article_info"></div> (index.html, line 30) and <div id="footer_info"></div> (index.html, line 44).

Next onto the JavaScript file main.js. There are two functions that do all of the work:

  • write_dimensions() (line 9) – this function takes the name of the HTML element, which is assigned to div_id in the function, and the name of the div where the output is going to be written, which is assigned to output_id.
function write_dimensions(div_id, output_id) {
    var div = document.getElementById(div_id);
    var div_info = document.getElementById(output_id);

    var w = Math.round(div.getBoundingClientRect().width * 100)/100;
    var h = Math.round(div.getBoundingClientRect().height * 100)/100;

    if (w > 400) {
        div_info.innerHTML = "<p>" + div_id + "-- " + " width: " + w +
                             " height: " + h + "</p>";
    } else {
        div_info.innerHTML = "<p>" + div_id + "--<br>" + " width: " + w +
                             "<br>height: " + h + "</p>";
    }
}

The first two lines of the function get the HTML elements, and the w and h variables are assigned the width and height, respectively. The key expressions here are div.getBoundingClientRect().width and div.getBoundingClientRect().height, the rest is just rounding to two decimal places. Finally, if the width is greater than 400px the div_info is assigned output on one line. However, if the width is less than or equal to 400px the output is split onto multiple lines – see the <br>‘s. This function handles the writing of the dimensions for all elements except the window.

  • write_window_dimensions() (line 26) – this function handles the dimensions for the complete window. The command for getting the window’s dimensions is slightly different from the generic HTML elements, so I have this separate function. The code for the function is:
function write_window_dimensions() {
    var header_info = document.getElementById("window_info");

    var width = window.innerWidth;
    var height = window.innerHeight;

    if (width > 445) {
        header_info.innerHTML = "<p>window-- width: " + width +
                                " height: " + height + "</p>";
    } else {
        header_info.innerHTML = "<p>window--<br>width: " + width +
                                "<br>height: " + height + "</p>";
    }

}

Comparing the above with the previous function– it should be easy to identify the different method for getting height and width. I don’t bother passing the HTML element and div id’s here because they are known and only take on one value that is hard-coded into the function.

With these two function defined, we can call them repeatedly. First, we call the function using the window.onload (top of main.js) to get the information when the page is first loaded. Next, we define a window.EventListener() that calls all of the functions whenever the window is resized. This enables the information about the dimensions to be updated as the window is resized.

So, that’s it for this post. In the future I’ll be using the code to work on responsive data visualization, which can respond to different screen sizes in useful ways. As always, comments are appreciated.

Tags

api [1]   arduino [1]   audio [2]   audio features [1]   babel [1]   Bayesian [7]   Beta [1]   blog setup [1]   bootstrap [1]   bottleneck [1]   c++ [1]   caret [1]   cmpy [1]   conditional probability [6]   coursera [1]   coursera intro to data science [3]   css [1]   cython [1]   d3 [2]   decision trees [2]   diy [1]   dropbox [1]   dsp [1]   e1071 [1]   essentia [1]   garmin [1]   geojson [1]   ggplot2 [1]   gis [2]   git [1]   gnuplot [1]   graphs [1]   html5 [1]   igraph [1]   ipython [1]   javascript [7]   joint probability [6]   json [1]   LaTeX [2]   LDA [1]   Lea [2]   machine learning [3]   marginal probability [6]   matplotlib [1]   meteor [2]   mir [1]   MongoDB [3]   music [2]   my python setup [5]   my ubuntu setup [10]   mysql [3]   networks [1]   networkx [1]   nodejs [5]   npm [3]   numexpr [1]   numpy [1]   octave [1]   Open Oakland [2]   openpyxl [1]   pandas [3]   patsy [1]   pip [2]   pweave [1]   pygraphviz [1]   pymc [1]   PySoundFile [2]   python [15]   Python [1]   python 2.7 [5]   python 3.4 [2]   pyyaml [1]   qgis [1]   R [1]   randomForest [1]   restview [1]   resume [1]   rpart [1]   running [1]   scikit-learn [3]   scipy [1]   screen [1]   server setup [1]   shapefile [1]   social networks [1]   Socrata [1]   sound [2]   sphinx [1]   sql [4]   sqlite3 [1]   ssh [1]   ssh keys [1]   statsmodels [1]   supervised learning [2]   sympy [1]   tableau [1]   tinkerer [2]   topic models [1]   tree [1]   ubuntu 14.04 [13]   Ubuntu 14.04 [3]   ubuntu 16.04 [4]   vim [2]   virtualbox [1]   virtualenv [4]   virtualenvwrapper [3]   VPS [1]   vundle [1]   webpack [1]   yaml [1]