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:
- check when we are in Portrait or Landscape mode
- 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.
No need for Jquery.
– Renan Gomes