2

Following this previous question JQuery distinct between smartphones, tablet or computers with different sizes but the same $(window).width() I now that I know the real sizes from the devices I use thank to window.screen.width , I would like to use one CSS file or another depending of this size, like for example:

<script>
var w = window.screen.width;
if(w < 800){
  //I should include somehow this <link href="{{ asset('assets/css/firstCSS.css') }}" type="text/css" rel="stylesheet">
} else {
  //Adding the second CSS file... <link href="{{ asset('assets/css/secondCSS.css') }}" type="text/css" rel="stylesheet">
}
</script>

I know this code looks horrible but I'm not able to get a solution.

(Edited)It is possible to use a css file depending on a value from JavaScript? Don't answer me yes... and show me how please.

3
  • 1
    Are you looking for media queries? w3schools.com/cssref/css3_pr_mediaquery.asp. If you want to make your site responsive to every device, try using media queries. Commented Aug 2, 2018 at 11:49
  • Take a look at this link. It might help. Commented Aug 2, 2018 at 11:49
  • Mediaquerys works like the $(window).width() values... I need this media queries but using the values from window.screen.width Commented Aug 2, 2018 at 11:50

1 Answer 1

4

Yes of course you can do it:

  • Create a new link element.
  • Give it a href based on your variable.
  • Append this link to the head of the document.

This is how should be your code.

var w = window.screen.width;
var link = document.createElement("link");
link.type = "text/css";
link.rel = "stylesheet";
if (w < 800) {
  link.href = "{{ asset('assets/css/firstCSS.css') }}";
} else {
  link.href = "{{ asset('assets/css/secondCSS.css') }}";
}
document.head.appendChild(link);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.