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

Initiate Action Upon Visibility

After discovering this script that creates a counting effect for numbers, I realized it starts animating as soon as the page loads. While I appreciate its functionality, I would prefer it to only initiate when the element is in view; otherwise, the animati ...

What is the most efficient method for storing and accessing a large matrix in JavaScript?

With 10000 items, creating a matrix of 10000 rows * 10000 columns using a one-dimensional array would be massive. Additionally, setting specific values to cells (i,j) where 0 < i, j < 10000 would require a large number of iterations. I am facing cha ...

Encountering an ongoing problem with trial repetition in JsPsych, which is causing the looping to continue endlessly without

As a beginner in JsPsych, I'm diving into creating a basic math quiz task to sharpen my skills. The goal is to generate random math questions as prompts and stop the task after 10 correct answers. I've managed to code that selects random math pro ...

Modify the data in a JSON array and receive the revised array using JavaScript

Within my JSON object, I have price values in numerical format. I am looking to convert these price values into strings within the same object My approach involves using the map function: var prods = [ { "id": "id-1", "price": 239000, "inf ...

Difficulty encountered with Mongoose/MongoDb FindOneAndUpdate functionality

My goal is to update a specific location only if it has a status of 0 or 2, but not if the status is 1. There is only one instance of this location in my database. Property.findOneAndUpdate({ status: 0, location: req.body.update.location }, req.body.updat ...

Enhanced tagging functionality in Knockout v3 with Chosen Multiselect

Recently, I have been expanding the functionality of a selected library by implementing an on-the-fly tagging feature using knockout observables to store the selected values. However, I have encountered some issues along the way. I am hopeful that someone ...

Adding turbolinks to an HTML document can be achieved without the need for a

Recently delving into the world of turbolinks, I discovered that it can be employed independently without relying on a client-side javascript framework. Eager to test this out, I created a bootstrap 4 template and attempted to install it. Firstly, I downl ...

Exploring the utilization of attributes with slots in Vue.js

Can attributes be set on a slot so that the element from the parent inherits those attributes? Parent <vDropdown> <button slot="button">new button</button> <ul>content</ul> </vDropdown> Dropdown.vue <d ...

The change event for the select element is malfunctioning

Currently, I am deep diving into Nodejs with the second edition of the node cookbook. This book has caught my attention because it explains concepts using practical sample code, making it easier to grasp. The example code I am working on is related to Br ...

New alternative for form-control-feedback in Bootstrap 4

The form-control-feedback class doesn't appear to be included in Bootstrap 4. What is the most effective way to achieve the desired outcome (an icon inside the textbox) using Bootstrap 4? <head> <link rel="stylesheet" href="https://max ...

Node.js Promise Rejection: TypeError - Unable to access property 'sign' because it is undefined

tran_script.js const CoinStack = require('coinstack-sdk-js'); const coinstackClient = new CoinStack('YOUR_COINSTACK_ACCESS_KEY', 'YOUR_COINSTACK_SECRET_KEY'); // Actual keys not displayed const privateKeyWIF = CoinStack.ECK ...

To view the element when the browser is not in full screen mode, the body overflow (both horizontally and vertically) can be used instead of resizing

I am trying to figure out how to create two vertical divs that stay the same size and height when the browser is not on full screen. I want users to be able to use the body's overflow scroll function to read both DIV elements along the x and y-axis. ...

Using Javascript to extract formatted text from a webpage and save it to the clipboard

I've developed a straightforward tool for employees to customize their company email signature. The tool generates text with specific styling, including bold fonts and a touch of color - nothing too extravagant. When I manually copy and paste the styl ...

Display the entire dataset retrieved from MongoDB and utilize the doT.js templating engine for rendering

I am facing an issue with extracting data from mongodb and passing it to the view. Despite all my efforts, only one record out of 10000 is showing up instead of all of them. I believe I am very close to resolving this problem but unfortunately, I am stuck. ...

Syntax for the "data" parameter in jQuery.ajax

I am attempting to send the contents of a JavaScript variable to the server for further processing. While I have no issue passing static strings, I encounter a problem when trying to pass a variable containing a string as the WebMethod fails to execute. He ...

The use of 'process.argv' and 'process.argv.slice(1)' does not seem to be functioning properly within Cypress

Currently, I am utilizing Cypress with JavaScript for my automation testing needs. My current task involves storing the user-passed command to run a script. Allow me to elaborate: Below is an excerpt from my package.json file: "scripts": { &q ...

Angular.js image slider display for viewing photos

Exploring the possibility of incorporating an open source widget to showcase images on a webpage, specifically leveraging angular.js. After conducting a search query on Google for "Angular.js photo carousel" or "angular.js photo viewer," I discovered only ...

Why is the leading zero being ignored when I try to print the contents of the session in PHP?

Encountering an issue with printing the content session. The problem arises when creating the session, as the variable is initially in string format (varchar obtained from a mysql field): Initial variable: 09680040 Printed with alert or displayed in div: ...

Error: Vue is unable to access the property '_modulesNamespaceMap' because it is undefined

I've been working on a simple web app to enhance my testing skills in Vue using Vue Test Utils and Jest. However, I encountered an error related to Vue while trying to console log and check if AddDialog is present in my Home file. The error message I ...

Struggling to integrate a functional update button into my Material UI datagrid version 5.6.1

I'm facing a challenge in adding a button to the rows of my Material UI DataGrid component. Here is my DataGrid component setup: <DataGrid rows={adminStorage} columns={columns} autoPageSize getRowId={(logistics) => logistics._id ...