How can I target specific screen sizes using JQuery instead of @media queries?

I am currently utilizing @media to define certain CSS styles, however now I require an equivalent check for screen size in JQuery.

@media ( min-width: 33em ) {

}

The goal is to hide a button when the screen size is larger than 33em, and to display it when the screen size is less than 33em.

Below is the button in question:

<asp:Button runat="server" ID="btnSelectAll" CssClass="btnSelectAll" data-theme="b"
                Text="Select All" OnClick="btnSelectAll_Click" />

Answer №1

Take a look at this jsFiddle demo: http://jsfiddle.net/A5Hk5/2/

To achieve what you need, simply monitor the screen width during window resize events. If the width falls below a specified value (in this case, 640px), hide the element; otherwise, display it.

This solution involves converting em units to pixels using conversion functions obtained from HERE.

$(document).on('pagebeforeshow', '[data-role="page"]', function(){ 
    $(window).resize();
});

$(window).resize(function() {
    $(".ui-btn").css({display: window.innerWidth >= $(33).toPx() ? "block" : "none"});
});

$.fn.toEm = function(settings){
    settings = jQuery.extend({
        scope: 'body'
    }, settings);
    var that = parseInt(this[0],10),
        scopeTest = jQuery('<div style="display: none; font-size: 1em; margin: 0; padding:0; height: auto; line-height: 1; border:0;">&nbsp;</div>').appendTo(settings.scope),
        scopeVal = scopeTest.height();
    scopeTest.remove();
    return (that / scopeVal).toFixed(8);
};


$.fn.toPx = function(settings){
    settings = jQuery.extend({
        scope: 'body'
    }, settings);
    var that = parseFloat(this[0]),
        scopeTest = jQuery('<div style="display: none; font-size: 1em; margin: 0; padding:0; height: auto; line-height: 1; border:0;">&nbsp;</div>').appendTo(settings.scope),
        scopeVal = scopeTest.height();
    scopeTest.remove();
    return Math.round(that * scopeVal);
};

Answer №2

If you're looking for a straightforward method, consider using a library like Enquire.js that allows you to implement media queries in JavaScript, similar to how you would in CSS.

Alternatively, if your goal is simply to display a button when the screen width is below 33em and hide it when it's above that threshold, you can directly check the screen width like so:

// Convert window width from pixels to ems, since ems are relative to font size
var widthEms = $(window).width() / parseFloat($('body').css('font-size'));

// Check for em width
if (widthEms < 33) {
    $('#btnSelectAll').show();
} else {
    $('#btnSelectAll').hide();
}

(Acknowledgment for the pixels-to-ems conversion: Is it possible to get the width of the window in em units using javascript?)

Answer №3

Obtaining the width of the viewport in jQuery is as simple as using $(window).innerWidth().

It is important to keep track of window resizing by using

$(window).resize( yourRedrawFunction )

Be cautious of converting pixels to em units. Width properties are typically in pixels, whereas you may require them in em units. This conversion can be challenging to calculate accurately, so it is advisable to avoid it if possible.

Here is a sample of it in action:

function redrawButton(){
    var pxPerEm = 13, // <- adjust as needed
        pxWidth = $(window).innerWidth(),
        emWidth = Math.round( pxWidth / pxPerEm );
    $('#btnSelectAll')[ width < emWidth ? 'hide' : 'show' ]();
    return true;
}
redrawButton();
$(window).resize( redrawButton );

To calculate the em size, one method is to extract the root font-size property from the CSS. However, this relies on the css property being present and correct. It might be safer to use a predetermined value, such as 13px as shown in my example.

var pxPerEm = /^(\d+)px$/.exec($(document.body).css('font-size')) ? Number(RegExp.$1) : 13;

Answer №4

Give this a shot:

if(window.innerWidth > 1000)
{
 ...
}

Experiment with em measurement, results may vary.

Answer №5

My recommendation would be to utilize the following code:

$(window).on('load', function () {
    var screenSize = { //consider setting this variable as global
        width: $(this).width(),
        height: $(this).height()
    };
});

If you are a conscientious developer who always sets width and height attributes for images and avoids using asynchronous scripts to re-render the DOM, it would be preferable to use the DOM ready handler:

$(function(){...}); //use $(window) inside handler

As a result, you can access the screen width using: screenSize.width

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

Regular Expression designed specifically for detecting alternative clicks

When using ngpattern for validation, I have encountered an issue where my error message is displaying for a different reason than intended. The error message should only show if the field is empty or contains only special characters. <textarea name="ti ...

Dynamic Creation of a jQuery Selector

Dear, I'm facing an issue while trying to load data dynamically into a table using JSON format. The data is coming from a PHP file. However, despite my attempts, the table remains empty and no data is being displayed. function fetchTableData() { ...

Collapsed Bootstrap navigation bar on mobile devices

Hello everyone, I am currently using the latest version of Bootstrap for my website. However, I have encountered an issue where the navigation collapses on mobile view. Could anyone provide assistance? Website: Below is a snippet of my HTML code: <he ...

Update the Bootstrap CSS styling of a button element following a user's click action

I am currently working with Bootstrap and facing an issue where I am trying to change the button color, but after clicking it and moving the mouse away, the color reverts back to blue. Here is the color I initially selected: https://i.sstatic.net/DCMq5.p ...

What is the best method for inserting a line break into a string?

Can you please explain how I can insert a line break into a string with JavaScript? I have tried using the <br/> tag, but it's not working. What is the correct way to achieve this? JavaScript var str="Click Here" +"<br>"+ "To Set" +"< ...

What is the best way to deactivate div elements once an overlay has been applied to them?

My goal is to place an overlay on my form to prevent users from accessing the content. Even though I have added an overlay, users can still interact with input fields. How can I prevent that? .overlay { background: rgba(0, 0, 0, .75); text-align: ce ...

The use of e.preventDefault in Ajax/jQuery is stopping the page from refreshing and preventing the form

Currently, I am experimenting with using ajax/jQuery/php/html to submit my form without reloading the page. If I include e.preventDefault(), the page remains static and the form does not get submitted. When I remove e.preventDefault(), the form gets submi ...

Query regarding timing in JavaScript

I recently started learning JavaScript and I am facing a challenge with running a check to determine if it is daylight. Currently, I am using Yahoo's weather API to retrieve information about sunrise and sunset times. The issue I have encountered is h ...

Is there a way to modify controller properties and values externally?

Just starting out with ember.js and encountering an issue. Once a form is submitted, jQuery sends a POST request (which is successful). However, I need the success function to update "val1" to "newVal". Any suggestions on how to achieve this? HTML: < ...

javascript/jquery - steps to design an effective modal page overlay

Struggling for the past few weeks to create a modal dialog using javascript/jQuery. While iOS and Android devices seem to work fine, Windows mobile/Opera mobile often present issues with the modal size. It either requires excessive scrolling or ends up bei ...

Expand the object by clicking on it, causing the surrounding objects to move outside the viewport instead of appearing below

I'm facing a challenge with 3 squares inside one container, each occupying 33.33% of the viewport and placed next to each other. When I click on one square, it should expand to full viewport width and reveal hidden content, while the other two remain ...

Utilizing JQuery and AJAX to update and save WordPress session variables

I am new to working with WordPress and encountering some challenges that I need assistance with. My objective is to update a session variable with the input provided by the user in a textbox. Once updated, I aim to save this session variable to a text fi ...

I'm having trouble getting the "flex direction: row" property to work within a table row

First, I applied flex to the table > tr. Next, I configured the flex-direction to be row. table { width: 100%; } tr { display: flex; flex-direction: row; flex-wrap: wrap; overflow: hidden; width:100%; } td:nth-child(1) { flex: 0 0 20%; ...

Discover the power of utilizing JavaScript to sort through table rows by filtering them based on the selections of multiple checkbox

How can I create interdependent logic for checkbox sections in a form to filter based on all selections? I am looking for help with my code snippet that showcases checkboxes controlling the visibility of table rows: $(document).ready(function() { $(" ...

The functionality of jQuery's onclick event is not functioning as intended

I have been struggling to make the onclick event work, but unfortunately it is not happening for me. Here is the code I am working with: HTML <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de" lang="de"> <head> ...

The Ajax post function behaves correctly in Chrome, however, no data is being received on the server when using Internet

Looking to fetch and manipulate an image (png) created by a flash application. When a user clicks on a link, this is what happens: var dataImgBase64 = document.getElementById("flashApp").getThumbnail(); The flash app then sends me the image in base64 for ...

What is the best way to conceal an element so that it only becomes visible when a user begins to input text

Hey there! I'm in the process of adding a search feature to my Jekyll site, and I've opted to use Simple-Jekyll-Search, which you can check out here: Link. Take a peek at what's inside my search.html: <input type="text" id="my-search-in ...

A seamless border encircling an inline span accompanied by consistent line spacing

I am trying to achieve a single contiguous outline around a <span> element nested within a <p> and <div>. I came across a solution here: CSS/Javascript: How to draw minimal border around an inline element? which works well except when the ...

Enhancing Your Website with Interactive Highlighting Tags

Looking at the following html: Let's see if we can <highlight data-id="10" data-comment="1"> focus on this part only </highlight> and ignore the rest My goal is to emphasize only the highlight section. I know how to emphasize a span ...

Issue with Ajax call not displaying the jQuery dialog box

Could you please take a look at this jsFiddle link... The issue lies with a jQuery UI dialog box that uses an ajax request to fetch content. Unfortunately, all I see is a blank dialog and can't seem to pinpoint the problem. A snippet of the HTML cod ...