Thursday, August 15, 2013

Dynamic Javascript based on CSS Media Queries

I am working on a project where I have to run different Javascript code determined on CSS Media queries. There is no built in way for doing this so I came up with this example.

I created two <div> tags, one with an ID of 'landscape' and another with an ID of 'portrait'. The CSS sets display:none; one and display:block; on the other depending on if the screen is in landscape or portrait mode.

When you click on the link in the example I use jQuery (you could use just Javascript) to check to see which of the two IDs are display:block. The function then returns the orientation value which is used as a dynamic object name and runs the version of the function that is for the current orientation, portrait or landscape.

This was a simple proof of concept, the real version I will be using will have multiple modes of display, phone, tablet(landscape), tablet(portrait) and desktop. This allows me to write all my functions and keep them in one object for each mode of display!

Example

Example Page

Code

<!DOCTYPE html> <html lang="en-us"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Responsive Javascript Example</title> <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" /> <style type="text/css"> <!-- @media only screen and (orientation:portrait) { html { background:white; color:black; } #portrait { display:block; color:red; } #landscape { display:none; color:red; } } @media only screen and (orientation:landscape) { html { background:black; color:white; } #portrait { display:none; color:green; } #landscape { display:block; color:green; } } --> </style> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/ecmascript"> /* <![CDATA[ */ jQuery.noConflict(); var landscape = {}; var portrait = {}; function orientation() { if (jQuery("#portrait").css('display') == 'block') { return 'portrait'; } if (jQuery("#landscape").css('display') == 'block') { return 'landscape'; } return 'unknown'; } window.addEventListener("load", function() { jQuery("a.layoutcheck").click(function(){window[orientation()].talk(); return false;}); }); landscape.talk = function() { alert('landscape'); } portrait.talk = function() { alert('portrait'); } /* ]]> */ </script> </head> <body> <h1>Responsive Javascript Example</h1> <p><a class="layoutcheck" href="">Click to check layout</a></p> <div id="landscape">Landscape</div> <div id="portrait">Portrait</div> </body> </html>