How to load a CSS file dynamically in jQuery?

0

I'm developing a mobile application on HTML , JavaScript and CSS using phonegap . I need to adjust / fit the same page layout for both portrait mode and landscape mode. My question is as follows when I identify the mode change, from landscape to portrait and vice versa, I want to load a CSS different, how do I load a CSS dynamically on a page using% with%?

    
asked by anonymous 02.11.2015 / 15:58

1 answer

2
  

If in jQuery it is not possible, and in JavaScript how do I?

jQuery is a javascript framework. His intention is to make it simpler what can be done with javascript . If it is possible in jQuery then it is possible in javascript .

  

How do I load a CSS dynamically into a page using jQuery

You do not necessarily need jQuery to do this. I'll show you a way to do it using javascript pure, and if you're interested, you can arrange the migration to jQuery .

For your algorithm we will basically need 2 steps:

  • check when in portrait or landscape mode
  • change the href attribute of a link tag to load the appropriate style
  • Checking the mode

    You can check the current mode using the following code:

    if (window.matchMedia("(orientation: portrait)").matches) {
        // MODO PORTRAIT
    }
    
    if (window.matchMedia("(orientation: landscape)").matches) {
        // MODO LANDSCAPE
    }
    

    You can also create a function that checks the size of the window if you want to change the style according to a certain width. This way you can create a style for small, medium, large, extra large devices. This is exactly what bootstrap does, however this is done through Media Queries and not javascript .

    Changing the href

    This part is relatively simple, you can create a link tag with any id and modify the href attribute according to the condition you want. Here is an example:

    <link rel="stylesheet" id="dynamic-link">
    
    <script>
    var dynamicLink = document.querySelector('#dynamic-link');
    
    if (CONDICAO DO MODO PORTRAIT) {
        dynamicLink.setAttribute('href', 'portrait.css');
    } else {
        dynamicLink.setAttribute('href', 'landscape.css');
    }
    </script>
    

    Media Queries

    Instead of loading files dynamically, you have the option of creating a single CSS file with some specific conditions, such as declarations that apply only in certain modes or resolutions. Here is an example:

    @media screen and (orientation:portrait) {  
        // ESTILO PARA MODO PORTRAIT    
    }
    
    @media screen and (orientation:landscape) {     
        // ESTILO PARA MODO LANDSCAPE   
    }
    

    Follow the especificação de Media Queries link for more information.

        
    02.11.2015 / 17:13