Tips for tailoring content based on screen size

I am looking for a way to display different content depending on whether the user is viewing my website on a large screen (PC/tablet) or a small screen (mobile). While my site is responsive and uses bootstrap, I have a lot of content that is only suitable for PC users, which can be overwhelming for mobile readers.

Is there a method to show different paragraphs and images when the site is accessed on smaller screens?

I have heard suggestions about using javascript or media queries for this purpose, but I am unfamiliar with these techniques. Could someone provide me with some sample code as I am new to handling such tasks?

Thank you

Note 1: This issue goes beyond just changing stylesheets. Instead of simply adjusting the format of the same content, I want to deliver entirely different content.

Note 2: I do not want to create a separate .mobi site as it could harm my existing search engine ratings.

Answer №1

If you're looking to achieve a specific goal, I recommend checking out this resource that shares similarities with what you have in mind: Prevent a video background from being downloaded on mobile browsers

To detect mobile devices, you can utilize the following code snippet:

function detectmob() { 

    if( navigator.userAgent.match(/Android/i)
    || navigator.userAgent.match(/webOS/i)
    || navigator.userAgent.match(/iPhone/i)
    || navigator.userAgent.match(/iPad/i)
    || navigator.userAgent.match(/iPod/i)
    || navigator.userAgent.match(/BlackBerry/i)
    || navigator.userAgent.match(/Windows Phone/i)
    ){

        // Perform actions specifically for mobile devices

    }
    else {

        // Handle non-mobile device scenarios

    }
} // detectmob

----------[ EDIT ]----------

var width = window.innerWidth;
var height = window.innerHeight;

if (width  > 480) {
    // Execute mobile-specific code
} else {
    // Implement other code
}

----------[ EDIT ]----------

To segregate content based on device type, create two separate files named mobile.html and desktop.html, assigning appropriate content to each one. Then, add the following javascript at the end of your main page:

function getFileContent(file) {
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function () {
        if (rawFile.readyState === 4) {
            if (rawFile.status === 200 || rawFile.status == 0) {
                var fileContent = rawFile.responseText;
                document.getElementsByTagName("body")[0].innerHTML = fileContent;
            }
        }
    }
    rawFile.send(null);
}

You can now use the above script to retrieve file contents and display them based on whether the visitor is using a mobile device or computer:

var width = window.innerWidth;
var height = window.innerHeight;

if (width  > 480) {
    // Execute mobile-specific code
    getFileContent("mobile.html");
} else {
    // Implement other code
    getFileContent("desktop.html");
}

That's the entire process! If you require further assistance, feel free to reach out.

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

Transforming a string into an array via AJAX response

I have been working on some ajax code that is returning an array as a string. My goal is to display either the first value or the second one in the array, like response.total or response[0]. When I check the response using console.log(response), here is w ...

Reducing Time Series Data: Comparing Average vs Largest-Triangle-Three-Buckets Technique

Currently, I am utilizing Flot Charts to create line charts that display timeseries data. To streamline the visualization process and reduce the number of data points shown, I have implemented a downsampling technique by averaging data points within the s ...

the battle between width and max-width for creating responsive web layouts

Many tutorials suggest using max-width:100% for images in responsive web design to ensure flexibility. However, why is it also possible to achieve the same result by using width:100%? ...

Issue with animated cursor function not activating when used with anchor links

I've spent hours searching for a solution but I can't seem to find one. I'm attempting to modify the codepen found at https://codepen.io/Nharox/pen/akgEQm to incorporate images and links, however, two issues are arising. The first issue is t ...

My simple application is experiencing a problem where ComponentDidMount is not being invoked

I used a tool called create-react-app to build this simple application. Strangely, the ComponentDidMount method is never getting invoked. import React, { Component } from "react"; class App extends Component { componentDidMount() { console.log("M ...

Guide to importing the Slider Component in React using Material-UI

I am trying to incorporate the Slider Component from @material-ui/core into my React project. However, when I attempt to import the Slider using this code: import Slider from '@material-ui/lab/Slider';, it gives me an error stating Module not fou ...

Capture user input to extract data from a JavaScript object

I need help with implementing a search function where users can enter a name and the person's extension will be displayed on the UI either by clicking a button or pressing "return". Any ideas on how to make this feature work seamlessly? UI <html ...

Can you provide step-by-step instructions on how to customize styles with MUI in my application?

I am encountering issues with MUI while attempting to customize the color of my buttons. The two methods I have tried so far have been unsuccessful. For example, Method 1: import React from 'react' import { Typography } from '@mui/material& ...

Can the conventional HTML context menu be swapped out for a link context menu instead?

Currently, I am working on developing a custom linkbox component that is similar to the one found on this page: Here is an example of the code: export const Linkbox = ({}) => { const linkRef = useRef(null); return ( // eslint-disable-next-l ...

"Troubleshooting a Responsive Design Problem: Horizontal Scroll Bar Appears on Low Res

My website is experiencing an odd issue with responsiveness. When viewed on desktop resolution in Chrome, there is no horizontal scroll. However, when I resize the browser to lower resolutions (400px width and less), the horizontal scroll appears. It see ...

Calculating the total length of an SVG element using React

Looking to animate an SVG path using React (similar to how it's done in traditional JavaScript: https://css-tricks.com/svg-line-animation-works/), but struggling when the path is created using JSX. How can I find the total length of the path in this s ...

Prevent jQuery from hiding elements when hovered over. Implement clearTimeout when hovering over an element, and use setTimeout when moving

I am attempting to create a sidebar with two navigation buttons that hide after a delay when the mouse cursor stops moving. However, I'm encountering an issue - how can I prevent these elements from hiding when they are in a hover state? Where should ...

Uncovering the source of glitchy Angular Animations - could it be caused by CSS, code, or ng-directives? Plus, a bonus XKCD comic for some light-hearted humor

Just finished creating an XKCD app for a MEAN stack class I'm enrolled in, and I'm almost done with it. However, there's this annoying visual bug that's bothering me, especially with the angular animations. Here is the link to my deploy ...

Programmatically link validation rules to form fields

I have implemented validation in a form using VeeValidate with Vue.js. Each input displays an error message related to the specific field where the error occurred. <div class="input-group"> <input type="date" class= ...

Positioning a button on the side of the screen while a hidden side panel is open

I am attempting to create an animation using a side panel that will slide into view when a button is clicked. Here is how it appears when the page loads: https://i.sstatic.net/JPQ2W.jpg When the user clicks on one of the buttons, the notes panel will be ...

The ESLint rule "eqeqeq" configuration is deemed incorrect

After successfully running eslint with the provided .eslintrc file, I encountered an issue when making a simple change to use 'standard' instead of 'airbnb-base' as the extend: module.exports = { root: true, parser: 'babel-esl ...

Combining href into click events - a step-by-step guide

I have an href link available. '<a href="index.php?imei=' + value['imei'] + '&nama=' + value['nama'] + '" class="summarykapal">Summary</a>' This is the function in question: function retr ...

Users using an iPhone are unable to adjust the scale or scroll on this website

I find myself wondering what I might be overlooking in this situation Here is the HTML code: <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="shortcut icon" href="../../nImg/favicon.ico" ...

Employ material-ui default prop conditionally

I am implementing a StepLabel component in material ui. Depending on the props passed to the parent, I may need to make changes to the icon property of the StepLabel: interface Props { customClasses?: ClassNameMap; customIcon?: ReactNode; } const MySt ...

Getting the most out of the fastest-validator package: Implementing multiple patterns and custom messages

Utilizing the powerful fastest-validator library for validation purposes. I have a requirement where the password field must contain at least one character and one number. Along with this, I am in need of specific messages for validating these conditions ...