How to load a CSS file dynamically in jQuery?

Asked

Viewed 1,227 times

0

I am developing a mobile application in HTML, JavaScript and CSS using the phonegap. I need to adjust / tailor the same layout of a page to both mode portrait how much for way landscape. My doubt is the following, when I identify the mode change, of landscape for portrait and vice versa, I want to carry a CSS different, how do I load a CSS dynamically on a page using jQuery?

1 answer

2


If jQuery is not possible, and Javascript as I do?

jQuery is a framework javascript. His purpose is to make what can be done in simpler javascript. Whether it is possible in jQuery then it is possible in javascript.

how do I load a CSS dynamically on a page using jQuery

You don’t necessarily need the jQuery to do this. I’ll show you a way to do it using javascript pure, and, if you are interested, you can arrange the migration to the jQuery.

For your algorithm we will need basically 2 steps:

  1. check when we are in Portrait or Landscape mode
  2. change the attribute href tag link to load the proper 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. That’s exactly what the bootstrap does, however this is done through Media Queries and not javascript.


Changing the href

This part is relatively simple, you can create a tag link with any id and modify the attribute href according to the condition you want. Follow 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 to create a unique CSS file with some specific conditions, such as statements that are applied only in certain modes or resolutions. Follow an example:

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

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

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

  • Thank you so much @Romulo!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.