Is it possible to restrict the application of jquery .css() to a particular media query only?

Whenever a user's browser width is below 1160px, a media query is set up to hide my website's right sidebar. They can bring it back by clicking on an arrow icon, causing it to overlap the content with absolute positioning.

To achieve this functionality, I utilized the following jQuery script:


$('.right_sidebar_preview').on('click', function() {
      $('.right_sidebar_preview').css('display', 'none');
      $('.right_sidebar').css('display', 'block');
});
$('.right_sidebar').on('click', function() {
      $('.right_sidebar_preview').css('display', 'block');
      $('.right_sidebar').css('display', 'none');
});

Essentially, I initially hide the preview when the browser viewport exceeds 1160px and keep the sidebar visible. However, under 1160px in the media query, the sidebar is hidden while the "sidebar preview" becomes visible for users to expand upon clicking.

CSS:


.right_sidebar {
  width: 242px;
  height: 100%;
  background-color: #d8e1ef;
  float: right;
  position: relative;
}
.right_sidebar_preview {
  display: none;
}
@media(max-width:1160px) {
    .right_sidebar {
        position: absolute;
        right: 0;
        display: none;
    }
    .right_sidebar_preview {
        display: block;
        background-color: #d8e1ef;
        position: absolute;
        right: 0;
        width: 15px;
        height: 100%;
    }
}

In using the aforementioned code, suppose we are within the less than 1160px media query, and after expanding and collapsing the sidebar, upon resizing the browser past 1160px again, it also closes the sidebar in the greater than 1160px media query.

Hence, I am curious if there exists a method like .css() (or any alternative means) to target a specific media query?

Answer №1

Avoid direct manipulation of the CSS display: property. Instead, utilize CSS classes to manage the visibility of the sidebar and its handle. By doing so, you can use media queries to determine whether an element should be displayed or hidden.

To see this concept in action on screens larger than 1160px, click the "Full page" button in the following demo.

$(function() {
  $('.right_sidebar, .right_preview').on('click', function() {
    $('.right_sidebar, .right_preview').toggleClass('lt-1160-hide lt-1160-show');
  });
});
.right_sidebar {
  width: 100px;
  height: 100px;
  background-color: papayawhip;
  float: left;
  display: block;
}
.right_preview {
  width: 20px;
  height: 100px;
  background-color: palegoldenrod;
  float: left;
  display: none;
}
@media(max-width: 1160px) {
  /* note: the following rules do not apply on larger screens */
  .right_sidebar.lt-1160-show, .right_preview.lt-1160-show {
    display: block;
  }
  .right_sidebar.lt-1160-hide, .right_preview.lt-1160-hide {
    display: none;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div class="right_sidebar lt-1160-hide">Sidebar</div>
<div class="right_preview lt-1160-show">&rsaquo;</div>

Answer №2

During a recent project, I encountered the need to execute a specific function in jQuery based on the size of the browser window. Initially, my approach involved checking if the device width was suitable for a mobile device (320px):

jQuery

$(window).resize(function(){

       if ($(window).width() <= 320) {  

              // your code here

       }     

});

Alternatively,

$(window).resize(function(){     

       if ($('header').width() == 320 ){

              // your code here

       }

});

Answer №3

Is this the desired format?

$(window).resize(function(){
   if ($(window).width() <= 1160){  
      // time to celebrate
   }    
});

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

the async function fails to run

fetchData = async () => { try { //Accessing data from AsyncStorage let car = await AsyncStorage.getItem('CAR') this.state.DatabaseCar=[]; this.state.DatabaseCar = JSON.parse(car); alert(this.state.Da ...

Even when the outcome is not what was anticipated, mocha chai still manages to ace the examination

When testing my REST API response with mocha, chai, and express, I set the expected status to 201 but unexpectedly got a passing test result it('janus post', () => { request('https://***') .post('/***') .attach(&a ...

Ways to expand the capabilities of Google Analytics for tracking AJAX requests and more, as recommended by the H5BP documentation

I need assistance with installing the Google Analytics enhancements mentioned in the extend.md file of H5BP (https://github.com/h5bp/html5-boilerplate/blob/v4.3.0/doc/extend.md). The documentation mentions using a specific code snippet for optimized Googl ...

Difficulty updating Material UI table

Currently in the process of updating my react site to version 16.8, I have encountered an issue with a material ui table. The functionality involves users selecting certain options, triggering a rest call when a button is clicked, and then displaying the r ...

Limiting access in _app.js using Firebase and Redux

In my application, users can access the website without logging in. However, they should only be able to access "/app" and "/app/*" if they are authenticated. The code I have written seems to work, but there is a brief moment where the content of "/app" ...

Balanced Columns with Background Extending Beyond Half of the Page

If you're looking for the final code, it can be found here: http://jsfiddle.net/asaxdq6p/6/ I am attempting to create an effect similar to this image: To achieve this, I am using the Equal Height Columns with Cross-Browser CSS trick as described in ...

Outputting HTML with functions

I have a function that returns HTML code. renderSuggestion(suggestion) { const query = this.query; if (suggestion.name === "hotels") { const image = suggestion.item; return this.$createElement('div', image.title); } ...

Utilizing Vue.js and Webpack to Handle Requests for Multiple Incorrect Resource Links

After utilizing Vue.js single file components to construct a website and appreciating the modular approach, I've encountered an issue. The browser appears to be requesting multiple versions of resources instead of just one URL for each. HeaderBar.vue ...

Effortless JavaScript function for retrieving the chosen value from a dropdown menu/select element

I've figured out how to retrieve the value or text of a selected item in a dropdown menu: document.getElementById('selNames').options[document.getElementById('selNames').selectedIndex].value In order to simplify this code, I&apos ...

Functions perfectly on Chrome, however, encountering issues on Internet Explorer

Why does the Navigation Bar work in Chrome but not in Internet Explorer? Any insights on this issue? The code functions properly in both Internet Explorer and Chrome when tested locally, but fails to load when inserted into my online website editor. Here ...

Angular is unable to fetch the chosen option from a dropdown selection

Recently, I encountered an issue with a module form that appears as a pop-up. Within this form, users can input data required to create a new object of a specific class. One field allows users to select a ventilation zone for the new room object being crea ...

Interactive CSS Video Gallery Slideshow

Is there a way to create a slideshow video gallery using CSS? I've looked everywhere but all I find are slideshow image galleries. If anyone has any resources or tips on how to do this, please share! This is the kind of video gallery I'm looking ...

Tips for utilizing <%= item %> in Jquery within EJS framework

Is there a way to utilize <%= item %> in jQuery within EJS? I understand how to use it within <html> tags, but I am curious if it can be utilized within <script> tags as well. <strong> <%= userx.email %></strong> Wha ...

why is it that I am not achieving the expected results in certain areas of my work?

I am facing issues with getting an alert response from certain buttons in the code. The AC button, EQUALS button, and the button labeled "11" are not behaving as expected. I have tried troubleshooting but cannot identify the problem. Can someone please ass ...

Compare the selected values of radio buttons with an array and find matches

I have multiple radio button groups, where each selection in a group corresponds to predefined values in an array. For example, selecting option 1 in Group 1 will increment values A and B by 1, while selecting option 2 will increment B, C, and D. The goal ...

Issue in Angular: Attempting to access properties of undefined (specifically 'CustomHeaderComponent')

I have encountered a persistent error message while working on a new component for my project. Despite double-checking the injection code and ensuring that the module and component export logic are correct, I am unable to pinpoint the issue. custom-header ...

Is that file or directory non-existent?

While working on developing a Discord bot, I keep encountering an error message stating: "Line 23: no such file or directory, open 'C:\Users\Owner\Desktop\Limited Bot\Items\Valkyrie_Helm.json']" even though the filep ...

Trying to filter out repetitive options in an autocomplete box

Using the jQuery autocomplete plugin, I am trying to display 5 unique search results. Initially, I achieved this by limiting the stored procedure to return only 5 results, but now I want to remove duplicates while still showing 5 distinct results. I'm ...

Is there a way to invoke a function within a mat-error element?

I need to display an error message in my input field! The function will return true if both passwords match, otherwise it will return false. How can I invoke a boolean function inside mat-error! My Function: checkPasswords(): Boolean { // 'passwords& ...

Disabling directional focus navigation in CSS: A comprehensive guide

Is there a way to disable directional focus navigation properties, such as 'nav-up', 'nav-right', 'nav-down', 'nav-left', for elements on an HTML page? button { position:absolute } button#b1 { top:0; left:50%; ...