Search code examples
cssmedia-queries

CSS for touch/no touch with small devices being marked as no-touch too


I'm using modernizer to add touch/no-touch to my pages and I currently have the following css:

.touch .desktop_only {
       display: none !important;
}
.no-touch .mobile_only {
       display: none !important;
}

I used to use:

@media only screen and (max-width: 1024px){
    .desktop_only {
       display: none !important;
    }
}
@media only screen and (min-width: 1025px){
    .mobile_only {
       display: none !important;
    }
}

I'm trying to sort of merge them so devices that are 1024px and smaller are also classed as touch devices, instead of no-touch devices...

At the same time, I'm also running into an issue where it temporarily loads both the desktop/mobile content at the same time for a split second.

Any idea how to do this, I'm sure it will be simple but I can't work it out at all.

I tried the code below, but that just makes lots of the css go weird because of the "intial"

@media only screen and (max-width: 1024px){
    .desktop_only {
       display: none !important;
    }
    .touch .desktop_only {
           display: none !important;
    }
    .no-touch .mobile_only {
           display: initial !important;
    }
}
@media only screen and (min-width: 1025px){
    .mobile_only {
       display: none !important;
    }
    .touch .desktop_only {
           display: initial !important;
    }
    .no-touch .mobile_only {
           display: none !important;
    }
}

Solution

  • You can use javaScript/jQuery to detect the touch devices and add or remove class accordingly.

    <script>
    $(document).ready(function() {
        var ua = navigator.userAgent;
        function is_touch_device() { 
            try {  
                document.createEvent("TouchEvent");  
                return true;  
            } catch (e) {  
                return false;  
            }  
        }
    
        if ((is_touch_device()) || ua.match(/(iPhone|iPod|iPad)/) 
        || ua.match(/BlackBerry/) || ua.match(/Android/)) {
            $('html').addClass('touch');
        } else {
             $('html').addClass('no-touch');
        }
    });
    </script>