Is It Possible to Run Javascript Code Based on a Specific Screen Size?

Here is the Javascript code I'm currently using to control the mobile menu functionality on my website. It prevents content outside of the menu from scrolling when the mobile menu is open and closes the menu when an item inside it is clicked.

document.getElementById('cp_toggle03').onchange = function() {
 if (document.getElementById('cp_toggle03').checked) {
 document.body.style.overflow = "hidden";
  } else {
 document.body.style.overflow = "";
  }

}


var elements = document.getElementsByTagName('li');
var closeHamp = function() {
 document.getElementsByClassName('cp_menuicon')[0].click();
    };



for (var i = 0; i < elements.length; i++) {
 elements[i].addEventListener('click', closeHamp, false);
    }

I am looking for a way to restrict this code to run only on specific screen sizes. I attempted to use the following Javascript to achieve that but encountered issues in getting it to work properly.

function execute(){
   if(screen.width <= 768) {
   
     }

If you have any suggestions on how I could modify this code to target a particular screen size effectively, please feel free to share your insights with me.

Check out My Website

Answer №1

One effective approach is to utilize a mix of JavaScript and the window.matchMedia method. By leveraging this method, you can set up a listener to detect screen size adjustments and selectively trigger specific actions based on predefined conditions.

Answer №2

Perhaps what you're seeking is document.body.clientWidth, which denotes the body tag's size (excluding borders, but including padding). The screen variable you mentioned reflects the actual screen width (e.g: 1920), so it remains constant even when the browser is resized.

Answer №3

The `Window` object available in JavaScript offers substantial capabilities. To access the width of your viewport minus the URL bar, you can utilize `window.innerWidth`.

When called, this method provides a `number` representing the width of the current viewport in pixels. Similarly, `window.innerHeight` gives the height.

For further details, check out the MDN link for window.innerWidth

To handle orientation changes from Portrait to Landscape, consider incorporating the 'onresize' event like this:

// window.addEventListener('onresize', method()); would also work, with "method" representing your logic

window.onresize = () => {
    if (window.innerWidth <= 768) {// switch to tablet sizes
        // code for mobile devices here
    }
}

Answer №4

Check out the js library https://github.com/WickyNilliams/enquire.js that enables dynamic responses to media queries.

An example of how it can be used:

    var matched = undefined;

    enquire.register("screen and (max-width:768px)", {
        match : function() {
            matched = true;
        },
        unmatch : function() {
            matched = false;
        }
    });
    
    function execute(){
       if(matched) {
            //perform certain actions
        } else {
            //perform other actions
        }
    }

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

Facing issues with the forEach method in ReactJs when attempting to access data from an array

Struggling with a ReactJS issue, I've come across a problem with the HomePage Component where the forEach method isn't working as expected. I'm attempting to retrieve data from a defined array. Take a look at the code snippet below: import R ...

What is the best way to dynamically resize the content inside a div element based on its dimensions using

My challenge is to create a centered div on the page that resizes with the viewport while maintaining an aspect ratio of 16:9. However, I also need the font and content inside the div to scale proportionally as it resizes. Using vmin works well in most cas ...

Exploring Node.js: Comparing Intl.NumberFormat and decimal.js library for floating point calculation

Can someone explain the distinction between Intl.NumberFormat and the decimal.js library? If Intl.NumberFormat can handle currency calculations, what is the purpose of using the decimal.js library and what advantages does it offer over Intl.NumberFormat ...

The current state of `this.router.getCurrentNavigation().extras.state` in Ionic is not defined

Seeking programming support once again. Allow me to elaborate on my issues and context. In Ionic, I am tasked with creating a tabs mobile application that prompts the user to enter a login/password to connect. Upon clicking the connection button, it shoul ...

Tips for incorporating transition animations into route changes in next.js

On the homepage, there are 2 links that I want to have distinct transition animations for. For example, if I click the link on the left, the animation should start from the left and move towards the right when changing routes. ...

Is it safe to enable HTTPS on my Glitch project even if my app is currently set up to use HTTP only?

I successfully created an http express app and placed it on glitch. Here is the code: const app = require('express')(); const express = require('express'); const http = require('http').createServer(app); app.use(express.stat ...

preclude any dates prior to the chosen date

I need a solution for a scenario where I have 5 datepickers in sequence. When I select a date on the first picker, all previous dates should be disabled when selecting on the next picker. Additionally, once a date is selected on one picker, the following ...

A `div` element with a height set to 100%, preventing the content from being scrollable

I've been struggling to make my content area (height:100%) scrollable, but have had no success. Despite trying various solutions, nothing seems to work. I'm using devextreme from DevExpress, but it shouldn't affect the CSS. I've set up ...

Enable express to disregard specific URL modifications

I'm currently working on creating a Single Page App using Express. One of the challenges I am facing is that the Express route feature forces the view to be re-rendered every time the URL changes and a GET request is sent to the server. My code typica ...

AngularJS: How to Implement Multi-select Functionality with Bootstrap Typeahead

I'm currently implementing bootstrap multiselect in my angular project (Bootstrap 2.3) My goal is to achieve a similar functionality using bootstrap typeahead, allowing users to select multiple values from search results. I've tried using the h ...

Altering the vertical position of <li> within the nav bar without impacting the size of the nav bar is proving to be a

How can I adjust the vertical position of li elements without impacting the height of the navigation bar? Below is the code snippet in question: body { margin: 0px; } ul { margin: 0px; padding: 0px; list-style: none; padding-left: 5px; pad ...

Achieving a Pushing Footer Design with Content

Hey guys, I'm working on a website and I'm having some trouble with the footer. It's sticking to the bottom of the page, but the content is overflowing it. Check out this screenshot for reference: . Here is my HTML/CSS code for the footer: ...

Utilizing media queries for responsive design in CSS

I've been working on aligning the page content for different browser sizes using CSS. However, I'm having an issue with the first @media statement - no matter what changes I make in there, it doesn't affect the layout. I've been using ...

Images fail to display on iOS devices using the Ionic Framework

I'm a beginner when it comes to the Ionic Framework, and I've encountered an issue with loading images. After receiving a list of image URLs from the server through a GET request, I can see the images' layout in Chrome's "Inspect eleme ...

How can I create a component that dynamically adjusts to different screen sizes

I have developed three child components for the main content area (excluding the header) However, one of the components is not responsive. Below is the code snippet: <div className="row" style={{marginTop:'30px',}}> <div class ...

Guidelines for capturing a div screenshot with javascript

Let's say I have a div containing an image source. <div> <p class="row">With custom CSS</p> <img src="/images/midhun.jpg"> </div> When a button is clicked, I want to display a screenshot of this image in another div. C ...

Can you tell me if there is a switch available for hover or mouse enter/mouse leave functions?

I have a series of div elements, each containing several nested div elements. I would like to add hover effects to these div elements. However, I am unsure whether to use the hover or mouseenter function. For instance, when hovering over a div, I want it t ...

Guide on programmatically choosing an option within a variable with the help of jQuery

Imagine having a variable named html, which holds select options like this: var html = '<select>'+ '<option value="10">10</option>'+ '<option value="20">20</option>'+ ...

Develop an Innovative Data-Driven Application using AJAX Technology

After inputting an artist's name and clicking on the button, I expect to receive a visually appealing list of their songs. I am encountering the following issue: Whenever I hit the button, no results are being returned, and I am unsure of the reaso ...

When used simultaneously, two jQuery functions fail to operate as expected

Currently in the process of coding my portfolio, I encountered an issue with incorporating two JavaScript/jquery codes together. Firstly, for the first section to be a full-page scroll using fullpage.js "plugin," and secondly, changing the navbar to be tra ...