ycfr6w
Last Updated: February 10, 2017
·
1.23K
· lugat
Dac8182499d9d16703b52d653806840b

Change JavaScript behaviour with CSS Media-Queries

If you need to trigger different JavaScript functions for different breakpoints, there is no need to check the window width by using JavaScript. Simply use CSS media-queries.

@media (min-width:768px) {
  .navbar-nav {
    content:'desktop'
  }
}
@media (max-width:767px) {
  .navbar-nav {
    content:'mobile'
  }
}

In JavaScript you then have the possibility to get the content attribute and trigger different functions, depending on its value.

var client = $('.navbar-nav').css('content');
if (client === '"desktop"') {
  // do smth.
} else {
  // do smth. else
}
Say Thanks
Respond

4 Responses
Add your response

17329
C9f74891ed55b2afdd0b79b1db52e4b5

A nice different approach, I have never thought of using this technique before. Usually I use a server side mobile detect library and pass the returned value to the window so I can access it when I please.

over 1 year ago ·
17350
None

Nice ! You could also use the matchMedia API, checking for media query in javascript only:

if (window.matchMedia('screen and (min-width:768px)').matches) {
// do smth
} else {
// do smth.else
}

over 1 year ago ·
17380
Thunderme

Wow this is a really good concept. Would have never thought of using content that way.

over 1 year ago ·
28595
Dac8182499d9d16703b52d653806840b

Of cause using matchMedia in JavaScript makes more sense :) This was just a funny thing I wanted to share and maybe someone will find a more "usefull" way to deal with it :)

4 months ago ·