Thursday, 2 January 2014

CSS3 MediaQuery events in JavaScript!

Friends,

Recently I came across some interesting elements in CSS3. Consider a responsive/fluid webapp where mediaqueries are used for different resolutions. Probably you might have defined all the required styles in the respective media-queries and the UI will render accordingly. But what if you want some additional stuffs to be done during that change? Today we will see how to resolve this issue.

New DOM events

There are different DOM events added after the introduction of CSS3. Few of them are animationStart, animationStop, transitionStart, transitionEnd etc. We will focus on animation events in this chapter.

matchMedia Web API

This API returns a new MediaQueryList object representing the parsed results of the specified media query string. You will find the details in the following code sample.


Code Sample

 <html>  
      <head>  
           <style>  
                body{  
                     background-color: yellow;  
                }  
                @media screen and (min-width: 400px) {  
                     body {  
                          -webkit-animation: anim1 2s;  
                     }  
                }  
                @media screen and (min-width: 800px) {  
                     body {  
                          -webkit-animation: anim2 2s;  
                     }  
                }  
                @-webkit-keyframes anim1 {  
                     0% {background-color: yellow;}  
                     50% {background-color: red;}  
                     100% {background-color: yellow;}  
                }  
                @-webkit-keyframes anim2 {  
                     0% {background-color: yellow;}  
                     50% {background-color: blue;}  
                     100% {background-color: yellow;}  
                }  
           </style>  
      </head>  
      <body>  
           <div id="animation"></div>  
           <div id="mediamatch"></div>  
           <script>  
                testMatch();  
                window.addEventListener('webkitAnimationStart', start, false);  
                window.addEventListener('webkitAnimationEnd', end, false);  
                function start(event) {  
                     document.querySelector("#animation").innerHTML = "animation started!"  
                }  
                function end(event) {  
                     document.querySelector("#animation").innerHTML = "animation stopped!"  
                }  
                function testMatch() {  
                     if(window.matchMedia) {  
                          var media1 = window.matchMedia("(min-width: 400px)");  
                          media1.addListener(listener1);  
                          var media2 = window.matchMedia("(min-width: 800px)");  
                          media2.addListener(listener2);            
                          listener1(media1);                           
                          listener2(media2);  
                     }  
                }  
                function listener1(queryList) {  
                     console.log("inside mat listener1"+queryList.media+ "->"+queryList.matches)  
                     if(queryList.matches) {  
                          document.querySelector("#mediamatch").innerHTML = "matchedMedia: (min-width:400px)";  
                     }  
                }  
                function listener2(queryList) {  
                     console.log("inside mat listener2"+queryList.media+ "->"+queryList.matches)  
                     if(queryList.matches) {  
                          document.querySelector("#mediamatch").innerHTML = "matchedMedia: (min-width:800px)";  
                     }  
                }  
           </script>  
      </body>  
 </html>  


Copy paste above content in your favorite text editor, save and open in a webbrowser. There are a few things done here.

What is written in style tag?

Style tag defines the background-color for html body. It also defines 2 mediaqueries for different widths. Each media-query has an animation using keyframe tag. Since webkit based browsers require -webkit- prefix, you may have to add it to the beginning.

In short CSS defines different background-color in different window sizes. Change your window size between 350px and 850px and you can see the difference.

What is there in JavaScript?

This is the part where we are interested in. Second and third statement inside JavaScript add listeners for animation start and stop events. And inside each listener, body content(innerHTML) is updated. This is evident when you resize your window. In fact this method is not recommended. What is recommended is the use of matchMedia API which you can find inside testMatch() method. You can pass a mediaquerystring and the API returns a MediaQueryList object which has got useful attributes such as media and matches. The former attribute gives the currently selected/chosen media-query whereas the latter returns true if the queryString matches with the currently chosen media-query.

Hope you enjoyed reading this. Happy coding!

No comments:

Post a Comment