Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// HTML:
<div class="display-type"></div>
// CSS:
// set the content of an element depending on the media query
@media (min-width: @screen-sm-min) and (max-width: @screen-sm-max) {
.display-type {
content: "tablet";
}
}
@media (max-width: @screen-xs-max) {
.display-type {
content: "phone";
}
}
// JAVASCRIPT
if($('.display-type').css('content') == "tablet"){
// Actions for tablets
}
if($('.display-type').css('content') == "phone"){
// Actions for smartphones
}
@jeremenichelli

This comment has been minimized.

Copy link

@jeremenichelli jeremenichelli commented Jul 1, 2014

Nice, I've used this approach. Also, the content checking should be place inside a resize listener function in case of resizing. Some tablets can have mobile layouts on portrait and tablet layouts on landscape.

@schierbeck

This comment has been minimized.

Copy link

@schierbeck schierbeck commented Jul 5, 2014

This is how I work with it in Sass. I like keeping media queries inside the element instead of the other way around. It is also nice to not have to have an extra html element imho. :-)

body:after {
    opacity: 0;
    position: fixed;
    content: "xs";

    @media (min-width: $screen-sm) {
        content: "sm";
    }
    @media (min-width: $screen-md) {
        content: "md";
    }
    @media (min-width: $screen-lg) {
        content: "lg";
    }
}
@murum

This comment has been minimized.

Copy link

@murum murum commented Jul 5, 2014

I saw jeremenicheills comment and why not work with the code something like this? I think it is slightly more structured, little bit more code but can be used multiple times without doing tons of DOM search for the class display-type etc.

// JAVASCRIPT
$(function() {
    var displayType = function() {
        return $('.display-type').css('content');
    }

    var display = displayType();
    $(window).on('resize', function() {
        display = displayType();
    })

    if(display == "tablet"){
      // Actions for tablets
    }

    if(display == "phone"){
      // Actions for smartphones
    }
});
@vilmosioo

This comment has been minimized.

Copy link

@vilmosioo vilmosioo commented Jul 7, 2014

@murum I'm afraid your code does not have any DOM access improvements. You should consider saving the element in a variable. :) Also, debounce your resize handler.
My 0.02

@vilmosioo

This comment has been minimized.

Copy link

@vilmosioo vilmosioo commented Jul 7, 2014

Awesome technique!

@breakerfall

This comment has been minimized.

Copy link

@breakerfall breakerfall commented Jul 8, 2014

Jeremy Keith wrote a bit about this technique too, back in the day

http://adactio.com/journal/5429/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment