Tips on precisely identifying a mobile phone using screen.availWidth without mistaking it for a tablet or a laptop

I am currently developing a gallery feature where I want to display portrait-oriented images to mobile phone users and landscape-oriented images to other devices like tablets and laptops.

Here is what I have so far:

var maxW = window.screen.availWidth * window.devicePixelRatio;

if (maxW <= 767){
    galleryImages = portraitImages;
}else{
    galleryImages = landscapeImages;
};

var portraitImages = [  'https://static.photocdn.pt/images/articles/2016-7/landscape-comp/iStock_000058793850_Medium.jpg',
 'https://keyassets.timeincuk.net/inspirewp/live/wp-content/uploads/sites/12/2016/05/AP_Portrait_Landscapes_Stu_Meech-5.jpg',
 'https://keyassets.timeincuk.net/inspirewp/live/wp-content/uploads/sites/12/2016/05/AP_Portrait_Landscapes_Stu_Meech-16.jpg', 
'https://static.photocdn.pt/images/articles/2016-7/landscape-comp/iStock_000062009934_Medium.jpg']

var landscapeImages = ['https://images.unsplash.com/photo-1506744038136-46273834b3fb?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjM3Njd9&w=1000&q=80', 
'https://images.unsplash.com/photo-1506260408121-e353d10b87c7?ixlib=rb-1.2.1&w=1000&q=80', 
'https://www.tom-archer.com/wp-content/uploads/2017/03/landscape-photography-tom-archer-4.jpg', 
'https://s.yimg.com/uu/api/res/1.2/DdytqdFTgtQuxVrHLDdmjQ--~B/aD03MTY7dz0xMDgwO3NtPTE7YXBwaWQ9eXRhY2h5b24-/https://media-mbst-pub-ue1.s3.amazonaws.com/creatr-uploaded-images/2019-11/7b5b5330-112b-11ea-a77f-7c019be7ecae', 
'https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/hbx030117buzz14-1550595844.jpg']

Now, assuming the smallest resolution for tablets is 768x1024. When I input 768x1024 in the Dev Tools resolution and run

alert("MaxW: " + maxW + ",\nMaxH : " + maxH);
, I receive MaxW: 1536, MaxH: 2048 due to the device-pixel ratio.

My question is, how can I accurately calculate the maximum screen size for a mobile phone, taking into account the device-pixel ratio?

I cannot simply use "show picture gallery if max-device width is 2048" because some computer monitors have lower resolutions.

I hope I have explained my query clearly. Please let me know if you need any more information or clarification.

Thank you for your assistance.

Answer №1

Utilizing the innerWidth and innerHeight properties of the window allows for the calculation of the screen width and height in pixels. On a screen with dimensions of 2560x1600, it returns the adjusted dimensions of 1280x800, factoring in the device-pixel ratio.

function getWindowDimensions() {
  const width = window.innerWidth;
  const height = window.innerHeight;
  const ratio = (width / height) * 100;
  return { width, height, ratio };
}

const { width } = getWindowDimensions();

if (width < 768) {
    galleryImages = portraitImages;
} else {
    galleryImages = landscapeImages;
}

Alternatively, instead of selecting images using JavaScript, the <picture> element with the srcset attribute can be utilized. By utilizing the <picture> element, media queries can be added to display images based on specific conditions set within those queries. This allows for inclusion of multiple image sets in the HTML, with the browser determining which image to display based on the query.

<picture>
  <source media="(max-width: 767px)" srcset="portrait.jpg">
  <source media="(min-width: 768px)" srcset="landscape.jpg">
  <img src="landscape.jpg" alt="Your image description">
</picture>

A recommended approach would be to create pairs for images within an array of objects, containing keys such as portrait and landscape. By iterating over the array, a <picture> element can be created for each pair, with corresponding <source> tags set to the appropriate media query and srcset value.

const images = [
  {
    portrait: './portrait-image-1.jpg',
    landscape: './landscape-image-1.jpg'
  },
  {
    portrait: './portrait-image-2.jpg',
    landscape: './landscape-image-2.jpg'
  },
  {
    portrait: './portrait-image-3.jpg',
    landscape: './landscape-image-3.jpg'
  }
];

for (const { portrait, landscape } of images) {

  const picture = document.createElement('picture');
  const sourcePortrait = document.createElement('source');
  const sourceLandscape = document.createElement('source');
  const image = document.createElement('img');

  sourcePortrait.media = '(max-width: 767px)';
  sourcePortrait.srcset = portrait;
  sourceLandscape.media = '(min-width: 768px)';
  sourceLandscape.srcset = landscape;
  image.src = landscape;

  picture.append(sourcePortrait, sourceLandscape, image);
  document.body.append(picture);

}

For device detection, such as identifying a mobile phone, checking the userAgent for specific keywords associated with phones is a viable option. While this method works well for device detection, it may not be as effective for responsive web development as new devices and browsers could be introduced in the future, potentially causing issues.

Answer №2

Is it necessary to assume that portrait mode equals phone and landscape mode equals tablet? I could very well be using my phone in landscape mode, especially when viewing a gallery.

Instead of jumping to conclusions about the device type, take a moment to determine the screen orientation in real-time. Adjust your software settings based on whether the screen is in landscape or portrait mode for maximum compatibility.

By doing so, your software will function seamlessly regardless of the device or orientation being used.

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

Making if-else statements easier

Greetings! I have a JSON data that looks like this: { "details": { "data1": { "monthToDate":1000, "firstLastMonth":"December", "firstLa ...

Controlling the Escape Key and Clicking Outside the Material-ui Dialog Box

I am currently utilizing material-ui's dialog feature. In this setup, when a user clicks the "sign out" button, a dialog box opens with options to either confirm the sign out by selecting "yes" or cancel it by choosing "no". The issue arises when the ...

Why isn't my watch function functioning properly within Vue?

In my JS file, I have two components. The file starts with this line: const EventBus = new Vue(); I am trying to pass two strings, 'username' and 'password', from the first component to the second component, but it's not working. ...

Why doesn't WebStorm display TypeScript inspection errors in real-time?

I'm currently utilizing WebStorm 2017.2.4 in conjunction with Angular 4.3 - I am facing an issue where TypeScript errors are not being displayed: https://i.sstatic.net/pcLQX.png Query How can I enable real-time inspections to occur immediately? (I ...

Steps for updating information in Firebase version 9

How can I add a new record and also change the 'bill' value, but I'm not sure what to input in this string? const newPostKey = (child(ref(db), )).key; This is the Vuex action I am using to make a request to Firebase: async updateInfo({ disp ...

Storing JSON information within a variable

I'm currently working on an autocomplete form that automatically populates the location field based on the user's zipcode. Below is the code snippet I've written to retrieve a JSON object containing location information using the provided zi ...

What could be causing the malfunction of my Nextjs Route Interception Modal?

I'm currently exploring a different approach to integrating route interception into my Nextjs test application, loosely following this tutorial. Utilizing the Nextjs app router, I have successfully set up parallel routing and now aiming to incorporate ...

The link in the drop down select is not functioning in IE8/9. When trying to open the drop down select link, an

Could use some help with IE8 and 9 compatibility, can't seem to find a solution. This code works smoothly on Chrome, FF, and Safari. There are two dropdown menus, each with two links. Every dropdown menu has its own "Buy Now" button. Upon selecting ...

How can you correctly make an Ajax request using computed properties sourced from VueX Store?

Is there a way to make an AJAX call where one of the parameters is a computed State in VueX? For instance, if I use this.$axios.get('someUrl/' + accID ), with accID being a computed property from VueX (using MapState), sometimes it returns ' ...

Tips on enclosing <li> elements within <ul> tags

Whenever I trigger the button within the .items class, it generates <li> elements in the following manner: <ul class="items"> <ul class="items"> <li>img1</li> ...

Adjusting the size of all elements on a webpage

Upon completing my project, I noticed that my localhost:3000 is zoomed in at 125%, causing it to appear less than ideal at 100% zoom. Is there a way to adjust the zoom/scale of my website to match how it appeared on my localhost environment? I came across ...

Is it possible to reset the existing localStorage value if we access the same URL on a separate window?

In my app, there are two different user roles: admin and super admin. I am looking to create a new window with a Signup link specifically for registering admins from the super admin dashboard. Is it possible to achieve this functionality in that way? Cu ...

Navigating through scroll bars in Reactjs

Currently, I am working on developing a React application, and I want to incorporate a full-screen title page as one of its key features. The challenge I am facing is related to the scrolling behavior on the title page. My goal is to have the page automati ...

In my app.post request in node.js and express, the body object is nowhere to be found

Having an issue with node.js and express, trying to fetch data from a post request originating from an HTML file. However, when I log the request, the req.body object appears empty. I've added a console.log(req.body) at the beginning of my app.post(" ...

How to add suspense and implement lazy loading for a modal using Material-UI

Currently, I am implementing <Suspense /> and lazy() to enhance the performance of my project. While everything seems to be working smoothly, I have observed some minor changes in DOM handling that are causing me slight confusion. Consider this scen ...

Trouble with Google Interactive Charts failing to load after UpdatePanel refresh

Desperately seeking assistance! I have spent countless hours researching this issue but have hit a dead end. My dilemma involves using the Google Interactive Charts API within an UpdatePanel to dynamically update data based on dropdown selection changes. H ...

Tips on how to properly handle Promises in a constructor function

My Angular Service is currently making http requests, but I am looking to retrieve headers for these requests from a Promise. The current setup involves converting the promise to an Observable: export class SomeService { constructor(private http: HttpCl ...

How to Stop AJAX Requests Mid-Flight with JQuery's .ajax?

Similar Question: Stopping Ajax Requests in JavaScript with jQuery Below is the straightforward piece of code that I am currently using: $("#friend_search").keyup(function() { if($(this).val().length > 0) { obtainFriendlist($(this).va ...

Knockout Mapping is causing a complete re-render of all elements

Utilizing the Knockout mapping plug-in to update the UI with JSON data fetched from the server every 3 seconds. The UI contains nested foreach bindings. However, it appears that all elements within the foreach bindings are completely erased and re-rendered ...

unable to attach picture to the img element

Currently, I am honing my skills in Windows Phone development through WinJS. In my latest project, I have crafted a code snippet that parses JSON data fetched from a specific URL. The objective is to bind the images retrieved to a list view on an HTML page ...