how to apply a css class only on mobile

-2

I'm using the latest version of OpenCart to create an online store, and I put the shopping cart in the navigation bar and I want it to be a dropdown when it's on a desktop and a drop-down menu when it's on a screen smaller. I was able to do the dropup part by adding the "dropup" class in the code as in the image below. I did not create this class I just applied from startup.

    
asked by anonymous 06.06.2016 / 22:50

1 answer

4

You can simply leave the work to the browser through a CSS Media Query:

@media only screen and (max-width: 760px) {
    /* esconde o elemento de controlo caso em Mobile */
    #el-controlo { display: none; }
}

On your page, you add an empty element that will be hidden when on mobile:

<span id="el-controlo"></span>

Finally, with jQuery you add the CSS class you want if your control element is hidden:

$( document ).ready(function() {

    // se elemento controlo escondido
    if ( $('#el-controlo').css('display')=='none' ) {

        // adiciona classe "dropup"
        $('#meu-elemento').addClass('dropup');
    }
});

The example above can be drastically reduced to a JavaScript condition using Window.matchMedia() :

if (!window.matchMedia("(min-width: 760px)").matches) {
    $('#meu-elemento').addClass('dropup');
}
    
11.06.2016 / 03:18