Poor man's responsive javascript

The other night I was wondering if there is a way to combine css media queries
and javascript to obtain a "responsive javascript". After around 10 minutes
of trial and errors I discovered it is.

The idea behind it is simple, you need to add a
"canary" element
to your html file like this:

<div id="canary_mobile"></div>

then use a css media query to change its state to discriminate between a mobile
browser and a desktop one.

#canary_mobile {
  visibility: hidden;
  display: block;
@media (max-width: 480px) {
  #canary_mobile {
    display: none;

In your javascript (assuming you have jQuery) you can query the canary to know
if the user is visiting the page from mobile or not

$(function() {
  function on_mobile() {
    return ($('#canary_mobile').css('display') === 'none');
  $('#btn').click(function() {
    if (on_mobile()) {
    } else {
      alert('not mobile');

Final Note

This is just a little experiment I made to satisfy my curiosity. If you plan to
do something similar in production you should use one of the many libraries