Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a browser event to catch when a css media screen query kicks in?

I'm making a js/jquery debug tool for personal use. I find it a pain in the ass to fine tune my css media screen queries. So I came up with an idea to display the triggered media css rules upon window resize. therefore I need to know if its possible to catch the event when a css media screen rule kicks in.

note: I could easily read my css files and put them in a variable and filter all media queries out and compare the screen value with the current window size. This will work but feels not efficient because all css files (and style tags) need to be processed. Are there other options?

like image 483
kasper Taeymans Avatar asked Nov 02 '22 12:11

kasper Taeymans


1 Answers

I found something in the dev pages from firefox. It is possible to get events when mediaqueries kicks in (and kicks out). Its pretty experimental but it does the trick.

Also there is no need to use regex to filter out media queries from the style sheets. This can be done by accessing -with js- the document style sheets (no need to load/ajax the sheets again) and check the CSSrule object names. it seems that css media query rules have an other objectname then normal css style rules. I recommend reading this interesting article. it's all explained there.

Firefox dev pages:

https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList

A MediaQueryList object maintains a list of media queries on a document, and handles sending notifications to listeners when the media queries on the document change.

This makes it possible to observe a document to detect when its media queries change, instead of polling the values periodically, if you need to programmatically detect changes to the values of media queries on a document.

Official specifications:

http://dev.w3.org/csswg/cssom-view/#the-mediaquerylist-interface

an other (edit: VERY) interesting article can be found here:

http://tylergaw.com/articles/reacting-to-media-queries-in-javascript

working example of what I want to do can be found here!!

http://tylergaw.github.io/media-query-events/

an other interesting project!

http://harvesthq.github.io/harvey/

like image 73
kasper Taeymans Avatar answered Nov 08 '22 03:11

kasper Taeymans