Identifying the loaded CSS with jQuery

My HTML page dynamically loads specific CSS files based on screen width (for PC, tablets, and phones):

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="all" href="css/style.css" >
<link rel="stylesheet" type="text/css" media="screen and (min-width: 1200px)" href="css/desktop-style.css" > 
<link rel="stylesheet" type="text/css" media="screen and (min-width: 769px) and (max-width: 1199px)" href="css/tablet-style.css" >
<link rel="stylesheet" type="text/css" media="screen and (min-width: 100px) and (max-width: 768px)" href="css/phone-style.css" >

I rely heavily on jQuery and need to select functions based on the active CSS. Is there a way in JavaScript or jQuery to determine which CSS is currently active? Or should I use jQuery to determine the browser width and then execute functions based on the width value? Thank you.

Answer №1

For more information, you might want to take a look at this discussion on the topic.

Consider incorporating media queries within your CSS stylesheet and loading it for varying screen sizes to optimize your layout.

Answer №2

If you're looking for a way to adjust your website layout based on different screen sizes, I suggest using media queries. However, if you prefer a JavaScript solution, you can achieve the same results using jQuery with the following code:

var window = $(window).width();
var css = $('#css');

if(window > 100 && window < 768){
  css.attr('href','css/desktop-style.css')
} else if(window > 769 && window < 1199){
  css.attr('href','css/tablet-style.css')
} else if(window > 1200){
  css.attr('href','css/phone-style.css')
}
<link id="css" rel="stylesheet" type="text/css" href="css/style.css" >

Please note that you can adjust the resolutions mentioned in the code as needed, but it may not be accurate for identifying mobile or tablet devices.

Warning: Keep in mind that this method may not be optimal for SEO purposes, as search engines like Google may not properly interpret your responsive styles.

Answer №3

One effective strategy is to check the width of the device before proceeding. However, there is a clever way to identify which CSS is being utilized by using a simple 'hack'. Simply assign a nonsensical property to a hidden element in each CSS file.

For example, in one CSS file you could have:

#canary {animation-name: first-css; display: none}

And in another CSS file:

#canary {animation-name: second-css; display: none}

You can assign a unique property to a specific element in each CSS file, which can then be checked using JQuery.

$(function() {
whichcss=$("#canary").css("animation-name");
$("#output").text(whichcss);
})
#canary {animation-name: first-css; display: none}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="canary"></p>
<p id="output"></p>

To ensure clarity, make sure to include the name of the CSS file within the properties in the following manner:

In desktop-style.css:

#canary {animation-name: desktop-css; display: none} 

In tablet-style.css:

#canary {animation-name: tablet-css; display: none}  

In phone-style.css:

#canary {animation-name: phone-css; display: none}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for retrieving a value from fs.accessAsync function

I am currently working on verifying the accessibility of a specific file, folder, or directory for reading purposes. I have implemented the code below, which functions properly. However, there are a couple of aspects that I would like to inquire about: 1. ...

Error encountered while trying to display the react-bootstrap table

I am having trouble rendering sample data using react-bootstrap tables. Every time I try, I encounter the error: TypeError: Cannot read property 'filter' of undefined I've searched on various platforms and visited multiple links, but I ca ...

Stop accidental clicking on objects in React-Fiber which are using Three.js

Check out this interactive cube made up of planes! An issue I've encountered is that clicking on a plane passes through to the ones behind it, rather than only registering a click on the plane directly under my mouse. Any suggestions for fixing this ...

Is there a way to prevent Prettier from automatically inserting parentheses for a single argument in an arrow function?

Currently, I've integrated Prettier into my workflow, but I've encountered an issue with arrow functions in JavaScript. For example: arg => console.log(arg) However, Prettier automatically formats it as: (arg) => console.log(arg) This for ...

The implementation of jQuery within an included HTML file may not function properly

I'm looking to implement the use of includes for generic HTML elements in my project. However, I've run into an issue where including an HTML file causes jQuery to stop working. Here is a snippet of my code that illustrates the problem. Specifica ...

The data type 'string[]' cannot be assigned to the data type '[{ original: string; }]'

I have encountered an issue while working on the extendedIngredients in my Recipe Interface. Initially, I tried changing it to string[] to align with the API call data structure and resolve the error. However, upon making this change: extendedIngredients: ...

Creating a Command Line Interface (CLI) application in JavaScript for the browser: A guide to simulating blocking I/O

Developing a CLI application becomes quite simple with a blocking I/O API like PrintLn / ReadLn, making the process smooth and efficient. However, the challenge arises when trying to create a terminal application that runs on a browser using JS. In this s ...

Creating a visually appealing user interface can be achieved by utilizing HTML/CSS to include bullet points and enumeration numbers in the page

I am looking for a way to display lists in a document with a style similar to the image on the right below: The text content of the list items is formatted like any other <p> and the bullet points are located in the margin. Is there a CSS solution ...

Utilizing Font Awesome within the `<fieldset>` element alongside Bootstrap 4 forms

When it comes to single-input forms in Bootstrap 4, a convenient method for incorporating font-awesome icons is by utilizing the input-group-addon class: <div class="input-group"> <span class="input-group-addon"> <i class="fa fa ...

Disabling pagination for custom searches in datatables

I need to implement a search filter based on only 2 columns using text fields. So, I have set up two text fields: <input type="text" id="type" name="type" placeholder="Filter by User Type"></td> <input type="text" id="dept" name="dept" pla ...

What is the best way to line up the columns of various divs?

Is there a way to align the content of these different divs? I'm trying to match up the headers of each column with the corresponding items in the divs below. Can someone assist me in achieving this alignment? row-header-course should align with cou ...

What is the best way to identify when the soft-keyboard is hidden in the Android browser

Having trouble with the Android Webkit browser and need to manually detect when the soft-keyboard is hidden by pressing the button in the top right corner. https://i.stack.imgur.com/x11Vp.jpg In the image above, pressing the button hides the soft keyboar ...

Investigating unsuccessful requests in node.js

Here is my code: var request = require('request'); function Service(){ this._config = require('../path/to/config.json'); } Service.prototype.doThing = function(){ return new Promise(function(resolve, reject){ request.post(url, ...

a pair of columns next to each other

I am having trouble getting two lists to display side by side. The second list keeps appearing below the first list. I need them to be in separate divs because they will have different colors and content. Additionally, the lists will be dynamically populat ...

Deactivating a form field depending on a selected radio button in Angular 2

If I have two radio buttons, with a click function called localClick for the first button to give value 1 and the second button to give value 2. <div class="ui-g-12"><p-radioButton name="group1" value="Local" (click)=localClick(1) label="Local"&g ...

Exploring the differences between an XMLHTTP request and a string and establishing a callback mechanism

After being a silent observer for quite some time, I've finally mustered up the courage to make my first post here, so please be kind... My journey with Javascript has just begun, and although I plan on delving into jQuery eventually, for now, I am f ...

What is the best way to determine if this statement is redundant or not?

I am attempting to generate a file with PHP that includes a substantial amount of HTML content and MySQL queries. The issue arises on line 3, indicated by the downward-facing arrow. The primary error identified is an excess of single inverted commas causi ...

Inquiry regarding the process of object creation in JavaScript

I recently discovered a method to create your own 'class' as shown below: function Person(name, age){ this.name = name; this.age = age; } Person.prototype.foo = function(){ // do something } Person.prototype.foo2 = function(){ ...

Apologies, but it seems there was an issue reading the "checked" property as it is null

I am currently facing an issue with the submit button in my Django application. It appears that the Javascript function is unable to determine which checkboxes are checked, as all I see in the console logs are "cannot read properties of null, reading "chec ...

inputting a pair of parameters into a function

While creating an action for react-redux, I encountered a problem when trying to pass two variables into the function - dispatch and hosts. Strangely, the variable host is being logged as a function instead of its actual value. This is my code: export fu ...