DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Databases
  4. Using Media Queries in JavaScript Code

Using Media Queries in JavaScript Code

Gil Fink user avatar by
Gil Fink
·
Dec. 10, 12 · Interview
Like (0)
Save
Tweet
Share
7.26K Views

Join the DZone community and get the full member experience.

Join For Free

using media queries in javascript one of the great additions in css3 is the ability to use media queries . media queries are queries written in css which enables you to check different medias types like screen, resolution, print and more. after the query check, you will be able to impose css as response for the media that was checked. this behavior occurs automatically but what if you want to check media and impose some logic that isn’t necessary related to style or responsive design? the answer will be discussed in this post.

pay attention the api written in this post is in draft state and it might change in the future.

using media queries in javascript

so you want to use media queries in your javascript code.

the first thing to know is the new mediaquerylist object. the mediaquerylist object is a list of all the media queries on the document object. the mediaquerylist object sends notifications to registered listeners when a media queries on a document change their state. the mediaquerylist object includes two functions which add and remove listeners: addlistener and removelistener . here is an example of adding an event listener:

mql.addlistener(handlescreenchange);

it also includes two properties:

  • matches : returns true if the document match the media query list, otherwise false.
  • media : the media query list stored in the mediaquerylist object.

in order to obtain a mediaquerylist object you need to use the matchmedia function. the matchmedia function receives a media query string and returns a mediaquerylist object. then, you can use the matches property to check the result of the query or add event listeners to handle media queries changes. the following example shows a script that is used to write to the console screen changes:

(function () {           
    function resize() {
        if (window.matchmedia('only screen and (max-width: 320px)').matches) {
            console.log('under 320 pixels');                    
        } else if (window.matchmedia('only screen and (min-width: 321px) and ' +
                                     '(max-width: 1024px)').matches) {
            console.log('between 320 and 1024 pixels');                    
        } else {
            console.log('higher than 1024 pixels');                    
        }
    }
 
    window.addeventlistener('resize', resize, false);
    resize();
}());

in the example, i’m registering to the window resize event. when a window resize happens, a check against the different media queries occurs and the relevant message is written to the console. you can avoid the registration to the resize event if you add a listener to the media query list:

(function () {
            function resize() {
                var mql = window.matchmedia('only screen and (max-width: 320px)').addlistener(function () {
                    console.log('under 320 pixels');
                });
                var mql1 = window.matchmedia('only screen and (min-width: 321px) and ' +
                                             '(max-width: 1024px)').addlistener(function () {
                                                 console.log('between 320 and 1024 pixels');
                                             });
                var mql2 = window.matchmedia('only screen and (min-width: 1025px)').addlistener(function () {
                    console.log('higher than 1024 pixels');
                });
            }
            
            resize();
        }());

pay attention to use the removelistener when you don’t need to get notifications when media query checks occur.

the support for the media query javascript api is available from chrome version 9, firefox version 6, ie10, and safari version 5.1. opera doesn’t support this api currently.

summary

media queries help to support responsive design that reacts to different media. when you want to use media queries from javascript you can use the mediaquerylist object and the matchmedia function.



Database Media queries Media (communication) JavaScript

Published at DZone with permission of Gil Fink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Exploring the Benefits of Cloud Computing: From IaaS, PaaS, SaaS to Google Cloud, AWS, and Microsoft
  • How to Quickly Build an Audio Editor With UI
  • Explainer: Building High Performing Data Product Platform
  • The Enterprise, the Database, the Problem, and the Solution

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: