Discover the dimensions of the viewport using jQuery

I am currently attempting to use jQuery to determine the size of the viewport, but I am not achieving the desired results.

Here is my CSS code:

.site {
    max-width: 960px;
}

@media only screen and (min-width : 760px) and (max-width : 1040px)  /* tablet */{
.site {
    max-width: 620px;
}

@media only screen and (min-width : 240px) and (max-width : 759px) /* mobile */{
.site {
    max-width: 285px;
}

I have attempted two different methods to determine the viewport size:

$(window).ready(function() {
    var viewport = $('.site').css("width");
});
$(function() {
    if ( viewport <= '285px' ) {
        console.log( "Mobile,", viewport ) ;}
    else if ( viewport <= '620px' ) {
        console.log( "Tablet,", viewport ) ;}
    else {
        console.log( "Desktop,", viewport ) };
});

However, this consistently returns "Mobile, 285px" regardless of the actual ".site" size. Changing ".css("width")" to ".css(width)" or ".width()" did not resolve the issue either.

The second method I tried was:

$(window).ready(function() {
    var viewport = $(window).width();
});
$(function() {
    if ( viewport <= 759 ) {
        console.log( "Mobile,", viewport ) ;}
    else if ( viewport <= 1040 ) {
        console.log( "Tablet,", viewport ) ;}
    else {
        console.log( "Desktop,", viewport ) };
});

Unfortunately, this always triggers an error in the console:

Uncaught ReferenceError: viewport is not defined 
(anonymous function) 
j 
k.fireWith 
n.extend.ready 
I

Changing "$(window)" to "$('.site')" also did not help to fix the error.

I am seeking guidance on what could be the issue here.

(To provide further context: My main goal is to adjust the negative margin of an off-canvas navigation to better fit the screen width. Please note that I am relatively new to using jQuery.)

Answer №1

Give this code a try:

$(window).ready(function() {
    var viewport = $(window).width();

    if (viewport <= 759) {
        console.log("Mobile,", viewport);
    } else if (viewport <= 1040) {
        console.log("Tablet,", viewport);
    } else {
        console.log("Desktop,", viewport);
    }
});

You can consolidate your code in the window ready block and eliminate the need for a second function.

Check out this fiddle for a demonstration

NOTE: The fiddle may display reduced results due to the width of the result section. Adjust the result section's width to observe changes in the width value.

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

Adjust the bootstrap switch component to be in the 'checked' state when the mode is set to Dark

I have stored a theme for my web application in the localStorage and I want to dynamically add the checked value to the Switch component if the mode is set to 'dark', or unchecked if the mode is 'light'. However, whenever I set the them ...

Struggling to insert a span element into an anchor tag within a dynamic WordPress navigation menu

I am currently attempting to insert a span tag within a tags in the secondary navigation located on the second level of the following page URL. Thus far, I have only discovered methods for adding span tags to the main navigation as well as child and grand ...

Divergent Bootstrap layouts for different devices

https://i.sstatic.net/g1YeJ.png I am working on creating a layout where I want to display certain content differently based on whether the user is viewing it on a mobile or desktop device. The current approach I have taken involves duplicating some divs ...

The styles within a media query are not being successfully implemented

update: issue resolved. I discovered that there was a lingering media query in the css file that was meant to be removed. Also, I corrected some errors in the code. Thank you all for your help – it's now working perfectly. I have a set of html and ...

"Experience a unique website layout with varying designs on desktop and mobile devices while using the React technology to enable desktop

Just starting out with React and I've noticed something strange. When I view my website on a PC, everything looks normal. However, when I switch to the desktop site on my phone, things appear differently. It seems like moving an element by 20px on mob ...

Working with HTML and JSP documents

After completing the front end of my webpage with an HTML file, I now need to fetch data from the server and display it on the webpage. It seems like using JSP is the way to go, but I'm concerned about adding Java code to my already large HTML file, m ...

Error: Property 'onclick' cannot be set on a null object

JavaScript isn't my strong suit, so I'm struggling to solve this issue. The console is showing me the following error message: Uncaught TypeError: Cannot set property 'onclick' of null <script> var modal = document.getE ...

Choosing the entire contents of a webpage using jQuery

Is there a way to use jQuery to select all the content on a webpage and copy it to the clipboard for use in another WYSIWYG editor? Here's the scenario: $("#SelectAll").click(function(){ //CODE TO SELECT ALL THE CONTENTS OF THE CURRENT PAGE /* PS: $ ...

What is the best way to vertically center text within a div?

After successfully centering my text horizontally in my div using text-align: center, I'm now faced with the challenge of centering it vertically. Despite my attempts with vertical-align: middle;, I haven't been able to achieve the desired result ...

Using a self-invoking function in JavaScript with addEventListener

I'm struggling to get an Event Listener to self invoke a function and work correctly. Although the following code runs the function, the Event Listener is not functioning as expected: window.addEventListener("resize", (function () { document.getElem ...

Bootstrap arranges checkboxes into three evenly spaced columns and centers them within a form

Having trouble organizing my checkboxes into 3 columns and centering them within the form perfectly. Current layout: Click here for image Desired look: Click here for image HTML: ` <form action="/signup" method="POST" ...

What is the process of incorporating a Higher-Order-Component in React?

I've been working on setting up a Higher Order Component (HOC) in React to enable text selection detection for any Input component. However, I seem to be missing a key piece of the puzzle in putting it all together. Initially, I followed an article t ...

Unauthorized HTTPS access using AJAX results in failure without a prompt asking for permission to proceed

After hours of frustration, I finally found the solution when I manually accessed the HTTPS server and encountered a security prompt: The site's security certificate is not trusted! Proceed anyway / Back to safety It turns out that when AJAX attempt ...

New feature incorporated at the end of choices in MUI auto-suggest widget

Currently, I'm working on enhancing a category adder feature. Previously, I had limited the display of the "add category chip" to only appear for the no-options render scenario. However, I came across an issue where if there was a category like "softw ...

Adding labels to a JavaScript chart can be done by using the appropriate methods

https://i.stack.imgur.com/uEgZg.png https://i.stack.imgur.com/y6Jg2.png Hey there! I recently created a chart using the Victory.js framework (check out image 1) and now I'm looking to incorporate labels similar to the ones shown in the second image ab ...

Bootstrap's innovative design for a data grid

I'm currently working on designing a Grid using bootstrap 3. https://i.sstatic.net/DZzcq.png My tools include html5, css, and bootstrap integrated with React.js. The main feature of my project is a data grid (specifically, a Fixed Data Table). ...

Steps to indicate a selected check column in a grid

I am working with a grid that has a check column, and I need to programmatically mark the checkbox. This is how the check column is coded: columns: { items:[ { itemId: 'checkColumn', xtype: 'selectallche ...

Creating a fixed navigation bar that stays at the top of the page when scrolling

I am trying to create a navigation bar similar to the one seen on W3School's website. I would like the navigation bar to overlap the header when scrolling down, and for the header to appear above the nav bar when scrolling back to the top. Despite m ...

Having trouble with fetching data in React from a URL?

When attempting to send a post request to a specific URL without proxy settings, I encountered a CORS error. After setting up a proxy, the URL was still pointing to localhost. The error persists even after attaching my proxyfile.js and including the code s ...

Node.js error message: Unable to load HTTP module

Recently starting with Node.js, I decided to install the latest version (4.2.1) on my Windows 7 PC. However, when trying to include the HTTP module by writing: var http = require("http"); I'm receiving an undefined error message. Can someone help me ...