Can a media query be activated based on a specific variable value?

I am looking to hide an element on my webpage if the screen width is less than 1000px and a specific variable is above 15.

Here is the CSS code I have so far:

@media (max-width: 1000px){
  #specific-id{
     display:none
   }
}

However, I need to incorporate JavaScript to ensure that this only happens when the variable is greater than 15. How can I achieve this control?

Answer №1

In my opinion, the most effective approach would be to include a class that is only applied if the variable exceeds 15:

If the variable is less than 15:

const variable = 0
const specificId = document.getElementById('specific-id')

if (variable > 15) {
  specificId.classList.add("variableIsMoreThan15")
}
#specific-id {
  background: red;
}

@media (max-width: 1000px){
  .variableIsMoreThan15 {
     display:none
   }
}
<div id="specific-id">
Hello
</div>

If the variable is greater than 15:

const variable = 16
const specificId = document.getElementById('specific-id')

if (variable > 15) {
  specificId.classList.add("variableIsMoreThan15")
}
#specific-id {
  background: red;
}

@media (max-width: 1000px){
  .variableIsMoreThan15 {
     display:none
   }
}
<div id="specific-id">
Hello
</div>

Answer №2

To create a custom media query, consider utilizing the following approach:

Check out this sample code snippet for guidance:

Start by defining a map that includes names and values for JavaScript variables. These values can be of different types such as MediaQueryList objects, booleans, numbers, or strings. For example:

<script>
CSS.customMedia.set('--bar', '20px');
</script>
<style>
@media (--bar: 20px) { ... }
@media (--bar > 15px) { ... }
</style>

Explore further details in the official documentation: https://www.example.com/custom-media-queries

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

Make sure to verify the existence of the data before trying to access it to avoid encountering an

Is there a more efficient way to handle data retrieval and avoid potential errors in React when accessing information from an API? The current code, although functional, appears to be quite repetitive. renderComicList() { var detail = this.props.ser ...

Achieving the display of font-weight 100 for Google web fonts successful

I have been experiencing difficulties in achieving the ultra-thin display of the Lato font through Google web fonts. Despite appearing correctly on Google's website, the font weight does not change when implemented on my own page if it is below 400 (I ...

Transforming the Looping Data in the GetJson Array into a Clickable Link

I am facing an issue with creating a list of markers on my Google Maps. I want to make a link that will display the values of each marker on the list, as it is looped through using getJson and <li> is only appended during the loop. Could someone ass ...

Issue with carousel functionality being disrupted by resizing of the window

I have lined up a series of 3 divs floating to the left in a straight line, each spanning the width of the page. Here is an example of the HTML structure: <div class="Horizontal-Wrapper"> <div class="Horizontal-Section"> <div ...

Table borders disappear when loading PHP echoed tables with jQuery and Ajax

Currently, I am delving into the world of jQuery, PHP, AJAX, and MySQL. My objective is to retrieve a table from the MySQL server and exhibit it on a webpage. This involves two PHP files – one serves as the back-end script connecting to the database and ...

JavaScript returns an undefined value when accessing a JSON array

I'm a beginner in the world of JavaScript and I find myself stuck on an issue. I've created a backend using Java SE, Jersey, and Jackson, everything seems to be running smoothly as my REST endpoint is up and running. However, I'm facing diff ...

Understanding Intl.NumberFormat: Languages and Currency Symbols

I want to implement the Intl.NumberFormat in my Angular6 Application to format currency. It works perfectly with USD, but when I try to use South African Rand or United Arab Emirates Dirham, I encounter a problem: I keep receiving a RangeError: Value R ou ...

Redirect middleware for Next.js

I am currently working on implementing a log-in/log-out feature in my project using nextjs, redux-saga, and mui libraries. // middleware.ts import { NextRequest, NextResponse } from 'next/server'; import { RequestCookies } from 'next/dist/c ...

Troubleshooting unexpected issues with dynamically updating HTML using innerHTML

Need help with a renderWorkoutUpdated function that replaces specific workout records with updated values. _renderWorkoutUpdated(currentWorkout) { let html = `<li class="workout workout--${currentWorkout.type}" data-id="${ curre ...

Opt for filling background image instead of stretching it when the screen is resized

My background image resizes with the screen height but stretches when I change the width. The content that should appear below it completely covers the image. This is my current code: HTML: <div id="bg"> <img src="http://placehold.it/2560x1 ...

How to transfer ID to another attribute within GridView in Yii2

Is there a way to transfer the ID from one column to another using JavaScript? Below is the code snippet in question: ['class' => 'yii\grid\SerialColumn'], 'alumni_id', /*This is the value I want to ...

Execute Two Functions When OnClientClick is Triggered

This is a snippet of my current code in progress <asp:LinkButton ID="lnkDel1" Text="Delete" runat="server" OnClientClick="return confirm('Delete this alert?','Confirm');" onClick="lnkDelete1_Click" CssClass="del_lnk" CommandArgumen ...

Utilizing JSX within this.state results in it being displayed as plain text when rendered

Currently, I am dynamically rendering a list of elements and I need to insert other elements in front of them based on key-value pairs. I want to utilize <sup></sup> tags for these elements, but they are appearing as plain text rather than sup ...

Issues with ion-textarea located within ion-item in IONIC 2 causing malfunction

I am experiencing an issue with an ion-textarea inside of an ion-item. Everything displays correctly, but as soon as I touch the textarea, the keyboard appears and then disappears. This makes it impossible to enter any text. It almost seems like the onblu ...

Tips for stopping the Bootstrap Modal from appearing every time there is a change event

Currently working on implementing conditional logic for certain products in our store, where a Bootstrap modal is displayed when a specific option is chosen by the user. My understanding of event bubbling is limited, but I have created variables for select ...

Managing file responses in Node.js

Hey there! I've been working on implementing ajax image upload and here's how far I've gotten. This is my index.html: <!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8> <title>File Upload ...

How can you use JavaScript to create hyperlinks for every occurrence of $WORD in a text without altering the original content?

I've hit a bit of a roadblock. I'm currently working with StockTwits data and their API requires linking 'cashtags' (similar to hashtags but using $ instead of #). The input data I have is This is my amazing message with a stock $sym ...

"Prisma vs. Supabase: A Comparison of Image Uploading

I am encountering an issue with adding image URLs to the Prisma database. I have successfully uploaded multiple images from an input file to Supabase storage, but when I try to add their URLs to the database, I receive an error regarding property compatibi ...

The deployment is currently being carried out

Here is the javascript code snippet I am working with: $scope.fav_details = function(id1,id2,bio) { document.getElementById(id2).style.display="none"; document.getElementById(id1).style.display="block"; $scope.getLegislatorDeta ...

Setting the default selected option in Vue for an object

Can the v-model data be different from the default option in this scenario? data: function() { return { user: { usertype: {}, } } <select v-model="user.usertype" class="btn btn-secondary d-flex header-input"> <option v-for= ...